Ruby on Rails - 为多个模型渲染 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4318962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby on Rails - Render JSON for multiple models
提问by freshest
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:
我正在尝试从 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
Any help would be much appreciated, thanks.
任何帮助将不胜感激,谢谢。
回答by Ryan Brunner
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 :includeargument to the render call, like so:
如果关联确实存在,您可以将:include参数传递给渲染调用,如下所示:
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_costsvariable in the section above if you take this approach, Rails will automatically load it from the @mouldingvariable.
请注意,@material_costs如果采用这种方法,则不必在上一节中检索变量,Rails 会自动从@moulding变量中加载它。
回答by iain
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.
一个控制器只能返回一个响应。如果您想将所有这些对象发回,您必须将它们放在一个 JSON 对象中。
How about:
怎么样:
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
回答by Bernard Banta
I did something like
我做了类似的事情
respond_to do |format|
format.html # show.html.erb
format.json { render :json => {:cancer_type => @cancer_type, :cancer_symptoms => @cancer_symptoms }}
here is the result
这是结果
{"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":[]}
So it is working
所以它正在工作
Thank you guys
谢谢你们

