急于加载“二级”的问题。相关对象 [英] Trouble on eager loading "second degree" associated objects
问题描述
我正在运行Ruby on Rails 3.1。我想急于通过应用某些条件来加载第二级关联对象,但我遇到了麻烦。
I am running Ruby on Rails 3.1. I would like to eager loading "second degree" associated objects by applying some conditions, but I am in trouble.
It seems that I already solved part of my issue by using:
article_categories =
article
.categories
.includes(:comments => [:category_relationships])
.where(:category_relationships => {:user_id => @current_user.id})
类别如下:
class Category < ActiveRecord::Base
has_many :comment_relationships
has_many :comments,
:through => :comment_relationships
...
end
class Comment < ActiveRecord::Base
has_many :category_relationships
has_many :categories,
:through => :category_relationships
...
end
上面的代码(它似乎做对了):
The above code (it seems to do it right):
- 通过照顾所有
类别
has_many:through
:category_relationships
关联(即通过关心.where(:category_relationships => {:user_id => @ current_user.id})
条件); - 渴望加载所有
article.comments.where (:user_id => @ current_user.id)
。
- loads all
categories
by caring thehas_many :through
:category_relationships
association (that is, by caring the.where(:category_relationships => {:user_id => @current_user.id})
condition); - eager loads all
article.comments.where(:user_id => @current_user.id)
.
不过,我想提出一些建议更多:
However, I would like to make some more:
- 要定购,通过检索到
类
:position
属性出现在category_relationships
中,因此生成的article_categories
是按位置排序; - 要增加负载也是
category_relationship
对象,其中user_id == @ current_user.id
,因为上面的代码没有做到这一点。
- to order retrieved
categories
by a:position
attribute present incategory_relationships
so that the resultingarticle_categories
are ordered by position; - to eager load also
category_relationship
objects whereuser_id == @current_user.id
since the above code doesn't make that.
如何利用急切加载的资源来实现这一目标?
推荐答案
解决方案:
-
.order( category_relationships.position)
.order("category_relationships.position")
想象一下,急切加载是笛卡尔积,并进行了一些过滤,因此 where正在过滤include的最终结果(实际上是左连接)。但这可以通过 where
和子查询来完成,子查询首先将按用户过滤类别,然后可以删除您的位置。
Imagine eager loading is cartessian product with some filtering so "where" is filtering the end result of include (left join really). But it can be done with where
with subquery which first will filter categories by user then your where can be removed.
这篇关于急于加载“二级”的问题。相关对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!