Ruby on Rails - 为多个模型渲染 JSON [英] Ruby on Rails - Render JSON for multiple models

查看:25
本文介绍了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

非常感谢任何帮助,谢谢.

Any help would be much appreciated, thanks.

推荐答案

实现此目的的一种方法是使用要渲染的对象创建哈希,然后将其传递给渲染方法.像这样:

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 参数传递给渲染调用,如下所示:

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 将自动从 @molding 变量中加载它.

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天全站免登陆