繁体   English   中英

Ruby on Rails - 为多个模型渲染 JSON

[英]Ruby on Rails - Render JSON for multiple models

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

  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

任何帮助将不胜感激,谢谢。

一种方法是使用要渲染的对象创建一个散列,然后将其传递给渲染方法。 像这样:

respond_to do |format|
  format.json  { render :json => {:moulding => @moulding, 
                                  :material_costs => @material_costs }}
end

如果模型未通过活动记录关联,那可能是您最好的解决方案。

如果关联确实存在,您可以将:include参数传递给渲染调用,如下所示:

respond_to do |format|
  format.json  { render :json => @moulding.to_json(:include => [:material_costs])}
end

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

一个控制器只能返回一个响应。 如果您想将所有这些对象发回,您必须将它们放在一个 JSON 对象中。

怎么样:

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

我做了类似的事情

respond_to do |format|
      format.html # show.html.erb
      format.json { render :json => {:cancer_type => @cancer_type, :cancer_symptoms => @cancer_symptoms }}

这是结果

{"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":[]}

所以它正在工作

谢谢你们

没有看到更复杂的例子,我想在下面抛出。

  def calculate_quote
    moulding = Moulding.find(params[:id])
    material_costs = MaterialCost.all

    respond_to do |format|
      # there times you'll need multiple formats, no need to overuse instance vars:
      format.html do
        @moulding = moulding
        @material_costs = material_costs
      end
      format.json do
        # in case of as_json, you can provide additional options 
        # to include associations or reduce payload.
        moulding_json = moulding.as_json
        material_costs_json = material_costs.as_json
        render json: {
           moulding: moulding_json,
           material_costs: material_costs_json 
        }
      end
    end
  end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM