Ruby on Rails - Render JSON for multiple models

freshest picture freshest · Nov 30, 2010 · Viewed 40.7k times · Source

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.

Answer

Ryan Brunner picture Ryan Brunner · Nov 30, 2010

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.