我有以下模型结构:
class Server < ActiveRecord::Base
has_many :websites
end
class Website < ActiveRecord::Base
belongs_to :server
has_many :plugins
end
class Plugin < ActiveRecord::Base
belongs_to :website
end
当我调用 server/1.json
时,我只得到 Server
属性的 JSON。我想要的是包括其所有 websites
和 websites
以包括其所有 plugins
。我将如何实现这一点?
format.json { render :json => @server.to_json(:include => :websites) }
这适用于包含网站
,但我也想包含网站内的引用。
最佳答案
你想要的是
format.json { render json: @server.to_json(include: {websites: {include: :plugins}}) }
您可以传入散列以包含而不是数组,并在这样做时指定嵌套包含。
关于ruby-on-rails - Rails to_json 包含多个 belongs_to 和 has_many 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16750776/