Ruby-on-rails Rails - 嵌套包含在 Active Records 中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24397640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails - Nested includes on Active Records?
提问by aryaxt
I have a list of events that I fetch. I'm trying to include every user associated to this event and every profile associated to each user. The Users get included but not their profiles.
我有一个我获取的事件列表。我试图包括与此事件关联的每个用户以及与每个用户关联的每个配置文件。用户被包括在内,但不包括他们的个人资料。
How Would i do this
我该怎么做
Event.includes(:users [{profile:}])
The docs don't seem to be clear: http://guides.rubyonrails.org/active_record_querying.html
文档似乎不清楚:http: //guides.rubyonrails.org/active_record_querying.html
回答by Joe Kennedy
I believe the following should work for you.
我相信以下应该对你有用。
Event.includes(users: :profile)
If you want to include an association (we'll call it C) of an already included association (we'll call it B), you'd use the syntax above. However, if you'd like to include D as well, which is also an association of B, that's when you'd use the array as given in the example in the Rails Guide.
如果你想包含一个已经包含的关联(我们称之为 B)的关联(我们称之为 C),你可以使用上面的语法。但是,如果您还想包含 D,它也是 B 的关联,那么您将使用Rails Guide 中示例中给出的数组。
A.includes(bees: [:cees, :dees])
You could continue to nest includes like that (if you actually need to). Say that A is also associated with Z, and that C is associated to E and F.
您可以继续像这样嵌套包含(如果您确实需要)。假设 A 也与 Z 相关联,而 C 与 E 和 F 相关联。
A.includes( { bees: [ { cees: [:ees, :effs] }, :dees] }, :zees)
And for good fun, we'll also say that E is associated to J and X, and that D is associated to Y.
为了好玩,我们还将说 E 与 J 和 X 相关联,而 D 与 Y 相关联。
A.includes( { bees: [ { cees: [ { ees: [:jays, :exes] }, :effs] }, { dees: :wise } ] }, :zees)
回答by Blaskovicz
If anyone is doing a respond_toblock to generate nested json, you can do something like:
如果有人正在执行respond_to块来生成嵌套的 json,您可以执行以下操作:
respond_to do |f|
f.json do
render json: event.to_json(include: {users: {include: :profile} }), status: :ok
end
end
回答by aschyiel
Please refer to Joe Kennedy's solution.
请参考乔肯尼迪的解决方案。
Here's a more readable example (for future me).
这是一个更具可读性的示例(对于未来的我)。
includes(
:product,
:package, {
campaign: [
:external_records,
{ account: [:external_records] },
{ agency: [:external_records] },
:owner,
:partner,
]
}
)

