【问题标题】:Rails to_json include multiple belongs_to and has_many referencesRails to_json 包含多个 belongs_to 和 has_many 引用
【发布时间】:2013-05-25 14:58:54
【问题描述】:

我有以下模型结构:

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。我想要的是包括其所有websiteswebsites 以包括其所有plugins。我将如何实现这一目标?

format.json { render :json => @server.to_json(:include => :websites) }

这适用于包含websites,但我也想在网站内包含参考。

【问题讨论】:

  • 既然你想获取连接到服务器的插件,你应该添加到服务器类has_many :plugins, :through =&gt; :websites并做@server.to_json(:include =&gt; [:websites, :plugins])
  • @Zippie 但这向我展示了服务器的所有插件。我想要属于它的网站的插件。该网站属于服务器。
  • 哦,对不起,误会了

标签: ruby-on-rails ruby json ruby-on-rails-3


【解决方案1】:

你想要的是

format.json { render json: @server.to_json(include: {websites: {include: :plugins}}) }

你可以传入一个哈希来包含而不是一个数组,这样做可以指定嵌套的包含。

【讨论】:

  • 太优雅了,我喜欢 Ruby=)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-20
  • 1970-01-01
  • 2023-03-10
  • 2014-10-23
相关资源
最近更新 更多