Rails - 嵌套包含在 Active Records 中? [英] Rails - Nested includes on Active Records?

查看:23
本文介绍了Rails - 嵌套包含在 Active Records 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我获取的事件列表.我试图包括与此事件关联的每个用户以及与每个用户关联的每个配置文件.用户会被包括在内,但不会包括他们的个人资料.

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.

我该怎么做

Event.includes(:users [{profile:}])

文档似乎不清楚:http://guides.rubyonrails.org/active_record_querying.html

推荐答案

我相信以下内容应该适合您.

I believe the following should work for you.

Event.includes(users: :profile)

如果您想包含已包含关联(我们称为 B)的关联(我们称为 C),您可以使用上述语法.但是,如果您还想包含 D,它也是 B 的关联,那么您将使用 Rails 指南.

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.

A.includes(bees: [:cees, :dees])

您可以继续像这样嵌套包含(如果您确实需要).假设 A 也与 Z 相关联,而 C 与 E 和 F 相关联.

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.includes( { bees: [ { cees: [:ees, :effs] }, :dees] }, :zees)

为了好玩,我们还将说 E 与 J 和 X 相关联,而 D 与 Y 相关联.

And for good fun, we'll also say that E is associated to J and X, and that D is associated to Y.

A.includes( { bees: [ { cees: [ { ees: [:jays, :exes] }, :effs] }, { dees: :wise } ] }, :zees)

这篇关于Rails - 嵌套包含在 Active Records 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆