One way you could do this is to create a hash with the objects you want to render, and then pass that to the render method. Like so.
Up vote 5 down vote favorite share g+ share fb share tw.
I am trying to render results from more than one model in JSON. The following code in my controller only renders the first result set: 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 much appreciated, thanks.
Ruby-on-rails json ruby-on-rails-3 render link|improve this question asked Nov 30 '10 at 21:39freshest603413 85% accept rate.
One way you could do this is to create a hash with the objects you want to render, and then pass that to the render method. Like so: respond_to do |format| format. Json { render :json => {:moulding => @moulding, :material_costs => @material_costs }} end If the models aren't associated through active record, that's probably your best solution.
If an association does exist, you can pass an :include argument to the render call, like so: respond_to do |format| format. Json { render :json => @moulding. To_json(:include => :material_costs)} end Note that you wouldn't have to retrieve the @material_costs variable in the section above if you take this approach, Rails will automatically load it from the @moulding variable.
Used your suggestion as well after finding this post. My models do have an association but I went with your first example as I feel it reads better. Thank you!
– Tass Mar 28 at 18:40.
A controller can only return one response. If you want to send all these objects back, you have to put them in one JSON object. How 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.
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 is working Thank you guys.
I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.