Render custom json polymorphic list - ruby-on-rails

I have a /tags.json where i want to render a list of players and teams, using the following which i have put in both players and teams model.
def token
"#{id}_#{self.class.name}"
end
Tags controller
def index
#players = Player.all
#teams = Team.all
#tags = #teams + #players
respond_to do |format|
format.json { render json: #tags}
end
end
But how can i create a list in my tags controller, so i can get something like this
[
{"name":"Bob","token":"1_Player"},
{"name":"Yankees","token":"1_Team"}
]
How can i do this?
Edit
format.json { render json: #tags.as_json(only: [:name])}
renders
[
{"name":"Bob"},
{"name":"Yankees"}
]
But how could i get token?

Try something like this:
#tags = []
Team.all.each do |team|
#tags.push({name: team.name, tag: team.token})
end
Player.all.each do |player|
#tags.push({name: player.name, tag: player.token})
end
respond_to do |format|
format.json { render json: #tags}
end

Related

How to fix an undefined method when relationship is established in the controller and table?

I'm trying to build a simple rails app. I have generated a model called cities and added a migration for city_name. Leveraging a form, I was to create my first city. However, when I go show.html.erb - I'm not able see my city name. Instead I'm prompted with an error "undefined method `city_name' for nil:NilClass"
I have pasted all my relevant code below. Any help would be greatly appreciated.
Cities Controller
class CitiesController < ApplicationController
def index
#cities = City.all
end
def new
#city = City.new
end
def show
end
def create
#city = City.new(city_params)
respond_to do |format|
if #city.save
format.html { redirect_to #city, notice: 'City was successfully created.' }
format.json { render :show, status: :created, location: #city }
else
format.html { render :new }
format.json { render json: #city.errors, status: :unprocessable_entity }
end
end
end
private
def city_params
params.require(:city).permit(:city_name)
end
end
Show.html.erb
<p>
<strong>
<%= #city.city_name %>
</strong>
</p>
<%= link_to 'Back', cities_path %>
Cities Model
class City < ApplicationRecord
end
I figured out what the mistake was, the issue is in the controller. I need to set up a before action and write out a method that would search for the param id of the specific city. My controller code is listed below for easy reference in case anyone else struggles with this.
class CitiesController < ApplicationController
before_action :set_city, only: [:show]
def index
#cities = City.all
end
def new
#city = City.new
end
def show
end
def create
#city = City.new(city_params)
respond_to do |format|
if #city.save
format.html { redirect_to #city, notice: 'City was successfully created.' }
format.json { render :show, status: :created, location: #city }
else
format.html { render :new }
format.json { render json: #city.errors, status: :unprocessable_entity }
end
end
end
private
def set_city
#city = City.find(params[:id])
end
def city_params
params.require(:city).permit(:city_name)
end
end
If you build a simple ruby on rails then here's show def
def show
#service_order = ServiceOrder.find(params[:id])
end
end

How do I create an instance variable in rails using OpenStruct

I would like to return facets along with the data in my controller. My code was :
def index
#people = Person.for_branch(session[:branch_id]).for_interests(params[:interest_search]).search_query(params[:search_term]).for_lead_sources(params[:lead_source_search]).page params[:page]
#organization = Organization.find(session[:organization_id])
#facets.total_count = Person.all.count
#facets.filtered_count = #people.count
respond_to do |format|
format.html
format.json {render partial: 'table.html', locals: { people: #people, organization: #organization, facets: #facets}}
end
end
However, I keep getting the error total_count is not defined.
undefined method `total_count=' for nil:NilClass
How can I fixed this?
I think you want to use OpenStruct variable.
require 'ostruct'
# ...
def index
#people = Person.for_branch(session[:branch_id]).for_interests(params[:interest_search]).search_query(params[:search_term]).for_lead_sources(params[:lead_source_search]).page params[:page]
#organization = Organization.find(session[:organization_id])
#facets = OpenStruct.new # initializing OpenStruct instance
#facets.total_count = Person.all.count
#facets.filtered_count = #people.count
respond_to do |format|
format.html
format.json {render partial: 'table.html', locals: { people: #people, organization: #organization, facets: #facets}}
end
end
Please note, that it is more convinient to use plain old Hash instead:
facets = {total_count: Person.all.count, filtered_count: #people.count}
respond_to do |format|
format.html
format.json {render partial: 'table.html', locals: { people: #people, organization: #organization, facets: facets}}
end
and use it in your views like this:
total count is <%= facets[:total_count] %>

Rails restful select in url

If I enter the following URL in a browser, I get a list of client records:
http://localhost:5000/clients.json
Now, I would like to be able the select certain clients via the URL. Is something like this possible:
http://localhost:5000/clients.json?locname=ys
This is my clients_controller.rb for index:
def index
#clients = Client.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #clients }
end
end
THANKS!
This should do the job:
def index
#clients = Client.scoped
#clients = #clients.where(:locname => params[:locname]) if params[:locname].present?
respond_to do |format|
format.html # index.html.erb
format.json { render json: #clients }
end
end

how can i include a variable at each array in rails?

I have user model and i want the list of users as json and i want the length of name along with the response for each user but i do not how i can do this? I have tried as shown below and it resulted in double render error. If i take the respond_to from the loop then it returns nothing. so please help me.
#users = User.all
#users.each do |user|
length = user.name.count
respond_to do |format|
format.json { render json: #users.to_json(:include => [:length]) }
end
end
I want the response to be like
[{"user":{"name":asgd,"id":1,"length":"4"}},{"user":{"name":asdfg,"id":2,"length":"5"}}]
Try:
#users = User.all
all_users = Array.new
#users.each do |user|
all_users << {"id" => user.id, "name" => user.name,"length" => user.name.size}
end
respond_to do |format|
format.json { render json: all_users.to_json }
end

How do I give a user access to show their own content OR public content in Rails?

Here is my current controller:
def show
#lesson = #current_user.lessons.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #lesson }
end
end
Currently users can only access their own lessons. If they go to example.com/lessons/[other person's public lesson id] then it doesn't show.
I would like to give users access to show their own lessons or other people's lessons if the lesson table's column public is true in the other person's lesson. How can I do that?
This seems to be working:
def show
begin
#lesson = #current_user.lessons.find(params[:id])
rescue ActiveRecord::RecordNotFound
#lesson = Lesson.where("public = ? AND id = ?", true, (params[:id]))[0]
end
respond_to do |format|
format.html # show.html.erb
format.json { render json: #lesson }
end
end
Is there anything unsafe or unsustainable about this?

Resources