Rails - Add index key for json parsed value - ruby-on-rails

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

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 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

RoR Response output type

I want my Rails rest application has json as default output format , also I want remove html format. Any suggestions? Thanks
Yes you can do it.
In your controller,
respond_to do |format|
#format.html # show.html.erb
#format.xml { render :xml => #post }
format.json { render :json => #post }
end
or you can handle it as javascript
respond_to do |format| format.js { render :json { :only => :name}.to_json end
then you just access your action with ".js" in the end
Try like this
format.any(:xml, :html, :json) { render :json => #post }

Is it a bug for method hash#to_json in Rails?

I use rails 2.3.8
def index
#posts = Post.all
respond_to do |format|
format.html # index.html.erb
format.json { render :json => ({ :results => #posts.size, :rows => #posts.to_json(:only => [:id, :title, :click_count, :body])}).to_json }
end
end
the generated json data is:
{"rows":"[{\"title\":\"ruby\",\"body\":\"goood\",\"click_count\":1,\"id\":1},{\"title\":\"g\",\"body\":\"h\",\"click_count\":1,\"id\":2}]","results":2}
but in fact is shuld be:
{"rows":[{\"title\":\"ruby\",\"body\":\"goood\",\"click_count\":1,\"id\":1},{\"title\":\"g\",\"body\":\"h\",\"click_count\":1,\"id\":2}],"results":2}
is it a bug in rails?
and now how can to_json generate the expected json data for me?
Thanks!
Sorry,it was my fault.
the action code should be
def index
#posts = Post.all
respond_to do |format|
format.html # index.html.erb
format.json { render :json => ({ :results => #posts.size, :rows => #posts.map{|x| x.attributes}).to_json } }
end
end
That is to say: the value of key :rows must be an array object!
Thanks hoooopo!

Resources