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

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.

Related

How to avoid the rendering to the next page

When I'm trying to download the CSV files it is rendering the next page, it should stay on the current page.
class EmployeeProofsController < ApplicationController
def index
#employeeproofs = EmployeeProof.all.order('id ASC')
respond_to do |format|
format.html { render "employees/index", :layout => false }
format.csv { send_data #employeeproofs.to_csv, :disposition => "attachment" }
end
end
end
Can any one tell me how to avoid the page rendering?
Remove the format.html part from your code along with this add , defaults: { format: :csv } to your route used for this action.

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

respond_with - How to respond with a text

I'm using the respond_to and respond_with in a rails app, but in one use case I need to respond with just a text for just one of the resource formats (:json)... But I can't find how to do this...
I want something like this (I know this doesn't work)
def create
...
respond_with(:json, render :text => "Successfully Done!")
end
Any Idea??
Thanks!
It seems that this may be what you are looking for:
def create
respond_to do |format|
format.html
format.json { render :text => "Successfully Done!" }
end
end
Andres,
The solution is this:
class TextController < ApplicationController
respond_to :json, :text
def index
respond_with do |format|
format.json {
render :text => "I'm a text provided by json format"
}
format.text {
render :text => "I'm a text"
}
end
end
end
And at your routes.rb:
match '/text' => 'text#index', defaults: { format: 'text' }

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!

How to convert records including 'include' associations to JSON

If I do something like:
result = Appointment.find( :all, :include => :staff )
logger.debug { result.inspect }
then it only prints out the Appointment data, and not the associated staff data.
If I do result[0].staff.inpsect then I get the staff data of course.
The problem is I want to return this to AJAX as JSON, including the staff rows. How do I force it to include the staff rows, or do I have to loop through and create something manually?
:include is an argument for to_json, not find. What you need to do in your controller is this:
def return_json
#appointment = Appointment.find(:all)
respond_to { |format|
format.json { render :json => #appointment.to_json(:include => :staff) }
}
end
You need to setup an association between Appointment and Staff for this to work.
Check out ActiveRecord::Serialization and ActionController::Base (see section: "Rendering JSON")
def show
#appointment = Appointment.find(:all, :include => :staff)
respond_to do |format|
format.html
format.js { render :json => #appointment.to_json(:methods => [:staff]) }
end
end

Resources