gpt4 book ai didi

ruby-on-rails - Rails to_json 包含多个 belongs_to 和 has_many 引用

转载 作者:数据小太阳 更新时间:2023-10-29 08:32:39 24 4
gpt4 key购买 nike

我有以下模型结构:

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) }

这适用于包含网站,但我也想包含网站内的引用。

最佳答案

你想要的是

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com