Ruby on Rails - Render JSON for multiple models

I am trying to map the results of more than one model to JSON. The following code in my controller displays only the first set of results:

def calculate_quote @moulding = Moulding.find(params[:id]) @material_costs = MaterialCost.all respond_to do |format| format.json { render :json => @moulding } format.json { render :json => @material_costs } end end 

Any help would be greatly appreciated, thanks.

+54
json ruby-on-rails ruby-on-rails-3 render
Nov 30 '10 at 21:39
source share
3 answers

One way to do this is to create a hash with the objects you want to render, and then pass this to the rendering method. For example:

 respond_to do |format| format.json { render :json => {:moulding => @moulding, :material_costs => @material_costs }} end 

If the models are not connected by an active recording, this is probably the best solution.

If an association exists, you can pass the :include argument to a render call, for example:

 respond_to do |format| format.json { render :json => @moulding.to_json(:include => [:material_costs])} end 

Note that you will not need to extract the @material_costs variable in the above section, if you take this approach, Rails will automatically load it from the @moulding variable.

+78
Nov 30 '10 at 21:48
source share

The controller can return only one response. If you want to send all these objects back, you must put them in a single JSON object.

What about:

 def calculate_quote @moulding = Moulding.find(params[:id]) @material_costs = MaterialCost.all response = { :moulding => @moulding, :material_costs => @material_costs } respond_to do |format| format.json { render :json => response } end end 
+7
Nov 30 '10 at 21:52
source share

I did something like

 respond_to do |format| format.html # show.html.erb format.json { render :json => {:cancer_type => @cancer_type, :cancer_symptoms => @cancer_symptoms }} 

here is the result

 {"cancer_type":{"created_at":"2011-12-31T06:06:30Z","desc":"dfgeg","id":2,"location":"ddd","name":"edddd","sex":"ddd","updated_at":"2011-12-31T06:06:30Z"},"cancer_symptoms":[]} 

So it works

Thanks guys,

+1
Dec 31 '11 at 15:00
source share



All Articles