Ruby on Rails-呈现多个模型的JSON [英] Ruby on Rails - Render JSON for multiple models

查看:84
本文介绍了Ruby on Rails-呈现多个模型的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从JSON中的多个模型中呈现结果.我的控制器中的以下代码仅呈现第一个结果集:

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

非常感谢您的帮助.

推荐答案

您可以执行的一种方法是使用要渲染的对象创建哈希,然后将其传递给render方法.像这样:

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.

如果存在关联,则可以将:include参数传递给render调用,如下所示:

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

请注意,如果采用这种方法,则不必在上一节中检索@material_costs变量,Rails将从@moulding变量中自动加载它.

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.

这篇关于Ruby on Rails-呈现多个模型的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆