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.
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:
I did something like
here is the result
So it is working
Thank you guys
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:
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: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.