I'm using Rails 4.2.7. When returning an object via a show method, I want to include an object from the object's parent. 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?
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,
@my_object.to_json(:include => [:parent, **:include** => :address])
so rails is searching include as one of the method or model.
You can use a array like this for including more than one relationship.
:include => [:parent, :address]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.