[英]When rendering an object in JSON from the controller, how do I include a field from the object's parent?
I'm using Rails 4.2.7. 我正在使用Rails 4.2.7。 When returning an object via a show method, I want to include an object from the object's parent.
通过show方法返回对象时,我想包含来自对象父对象的对象。 I tried
我试过了
def show
respond_to do |format|
@my_object = MyObject.find(params[:id])
format.json { render :json => @my_object.to_json(:include => [:parent, :include => :address]) }
end
end
However this is producing the error 但是这会产生错误
NoMethodError (undefined method `include' for #<MyObject:0x007fa1b433d788>):
What's the right way to include an object from my parent? 包含我父母的对象的正确方法是什么?
Edit: here's the parent model in my Rails app
编辑:这是我的Rails应用程序中的父模型
class Parent < ActiveRecord::Base
belongs_to :address, :autosave => true #, dependent: :destroy
Try this one 试试这个
def show
@my_object = MyObject.find(params[:id])
render :json => @my_object.to_json(:include => [:parent => {:include => :address}])
end
You have added include within the include statement, 您已在include语句中添加了include,
@my_object.to_json(:include => [:parent, **:include** => :address])
so rails is searching include as one of the method or model. 因此,Rails正在搜索包括作为方法或模型之一。
You can use a array like this for including more than one relationship. 您可以使用这样的数组来包含多个关系。
:include => [:parent, :address]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.