在 activerecord 中包含自引用模型,并根据包含的模型从两者中进行选择
对于相当令人困惑的标题表示歉意,我发现很难正确地表达这个问题。
我有一个模型,将其称为 Thing
,即 has_many :lated_things
、has_many :linked_dates
和 has_many :assignments
(用户分配给事物)。我想进行一个查询来选择用户分配到的事物中的所有关联日期,以及相关事物中的所有关联日期。
目前,我有这个方法可以获取直接分配的关联日期:
AssociatedDate.includes(:thing)
.includes(:thing => :assignments)
.where('assignments.user_id' => id)
但是,我尝试加载通过 :lated_things
相关的日期的尝试未加载。我得到的最接近的只是在查询中包含 :lated_things
:
AssociatedDate.includes(:thing)
.includes(:thing => [:assignments, :related_things])
.where('assignments.user_id' => id)
但是我不知道从那里去哪里,并且它本身不会对查询的结果产生任何影响询问。我想要的选择是否可能,我将如何去做?
Apologies for the rather confusing title, I'm finding it rather difficult to phrase this question properly.
I have a model, call it Thing
that has_many :related_things
, has_many :associated_dates
and has_many :assignments
(users assigned to things). I want to make a single query to select all associated dates from a Thing
which a user is assigned to, as well as all associated dates from the related things.
At the moment, I have this which works for getting the associated dates which are directly assigned:
AssociatedDate.includes(:thing)
.includes(:thing => :assignments)
.where('assignments.user_id' => id)
However, my attempts to also load those dates that are related through :related_things
are not loaded. The closest I've got is just including the :related_things
in the query:
AssociatedDate.includes(:thing)
.includes(:thing => [:assignments, :related_things])
.where('assignments.user_id' => id)
But then I don't know where to go from there and on its own this does not have any effect on the outcome of the query. Is the select I want possible, and how would I go about doing it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你需要
加入
。请查看此处的文档。类似于AssociatedDate.joins(:thing).joins(:thing=>:lated_thing)
I think you need
joins
. Have a look at the documentation here.Something like
AssociatedDate.joins(:thing).joins(:thing=>:related_thing)