how can i include a variable at each array in rails? - ruby-on-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

Related

Rails - How to render json with extra field in index controller method

I'm using Rails 4.0.2 with paperclip for image upload in my project. Also I need to send a full image path of paperclip. So I can do it with add new field and set image path manually in my show controller method for particular record.
show
def show
respond_to do |format|
format.html
format.json { :json => JSON::parse(#demo.to_json.merge("new_field" => #demo.image_url.url).to_json}
end
end
When I view Json for any of my record, this is will showing good.
{
id: "1",
name: "demo",
new_field: "/demo/1/original/file.jpg"
}
In same scenario, I need to get the full image path of paperclip image for all records when I am requesting to index method on controller
index
def index
#demos = Demo.all
respond_to do |format|
format.html
format.json { :json => Demo.all.to_json}
end
end
I tried some of codes, but I don't know how exactly to write
def index
#demos = Demo.all
#demos.each do |demo|
new_field = {"new_field" => #demo.image_url.url}
# After I stucked with logic, how to uppend with 'demo'.
end
respond_to do |format|
format.html
format.json { :json => Demo.all.to_json}
end
end
How do I iterate my individual Demo model and How to merge full image path into each record.
I found the solution for my question,
def index
#demos = Demo.all
#demos_data = []
#demos.each do |demo|
new_field = {"new_field" => #demo.new_field.url}
demo = JSON::parse(demo.to_json).merge(new_field)
#demos_data << demo
end
respond_to do |format|
format.html
format.json { :json => #demos_data}
end
end
I suggest you to use two approaches, 1)use active model serializer to expose json response. 2) use jbuilder library to expose custom fields. Still you need help please let me know.
Try this:-
def index
#demos = Demo.all
#demos_data = []
#demos.each do |demo|
demo["new_field"] = #demo.image_url.url
#demos_data << demo
end
respond_to do |format|
format.html
format.json { :json => #demos_data}
end
end
maybe you can try:
def index
#demos = Demo.all
#demos.map do |demo|
new_field = {"new_field" => #demo.image_url.url}
demo.attributes.merge(new_field)
end
respond_to do |format|
format.html
format.json { :json => #demos}
end
end
attributes method returns a hash of all the object attributes, just need merge new key-value into the returned hash.
Another way of doing it is in your controller where you are rendering the json
render json: #merchants,
include: {
offers: {
except: [:created_at, :updated_at],
include: {
categories: {
except: [:created_at, :updated_at]
}
}
},
location: {
methods: :country_name,
except: [:created_at, :updated_at]
}
},
except: [:created_at, :updated_at]
Note the methods: :country_name, there you can render methods from your model as json attributes. and through include: ... you can eager load and render related models.

Rails - Add index key for json parsed value

I am using rails 4.0.2. For my mobile api, I need to send JSON values to that. Here I face some problems to sending JSON . I want to customize my JSON with index key
For example, when I request index of my cities controller,
http:localhost:3000/cities.json
I got JSON value like this,
[
{"id":1,"name":"AAAA"},
{"id":2,"name":"BBBB"},
{"id":2,"name":"CCCC"}
]
But I want to surrounded with some named object or array.
{
"cities" :
[
{"id":1,"name":"AAAA"},
{"id":2,"name":"BBBB"},
{"id":2,"name":"CCCC"}
]
}
Now I tried in my controller,
def index
#cities = City.all
respond_to do |format|
format.html
format.json{ render :json => #cities.to_json(:methods => [:image_url]) }
# :methods => [:image_url] this is related to paperclip gem
end
end
Try this first as:-
def index
#cities = City.all
cit ={'cities' => #cities}
respond_to do |format|
format.html
format.json{ render :json => cit}
end
end
After that try as:-
def index
#cities = City.all
cit ={'cities' => #cities}
respond_to do |format|
format.html
format.json{ render :json => cit.to_json(:methods => [:image_url]) }
end
end

Render custom json polymorphic list

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

To display the searched item in the same page

The following code present in srches_controller
def index
#srches = Srch.all
respond_to do |format|
format.html # index.html.erb
format.json { render :json => #srches }
end
.
.
.
def search
#srch=Srch.find(:all,
:conditions => ["name LIKE ? OR address LIKE ?", "%#{params[:search]}%", "%#{params[:search]}%"])
end
The searched item is now displayed in the new search page.
But I need to display the searched item in the same index page.
What is the solution?
You can pass parameter search to index page and search your results with:
def index
#srches = Srch.scoped
if params[:search].present?
#srches = #srches.where(['name LIKE ? OR address LIKE ?', "%#{params[:search]}%", "%#{params[:search]}%"])
end
respond_to do |format|
format.html
format.json { render :json => #srches }
end
end
or you can set scope in your model:
scope :search, lambda{|query|
if query.present?
where(['name LIKE ? OR address LIKE ?', "%#{query}%", "%#{query}%"])
end
}
and call it in controller with:
#srches = Srch.search(params[:search])
You can use meta search gem for your index method, it looks some thing like this -
def index
#srches = Srch.search(params[:search])
respond_to do |format|
format.html # index.html.erb
format.json { render :json => #srches }
end
In this case if search parameters were present it will search in your table else it will return all the records from your table.

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

Resources