急于加载“二度”关联对象的麻烦
我正在运行Ruby on Rails 3.1。 我想通过应用一些条件来加载“二度”关联对象,但我遇到了麻烦。
似乎我已经使用以下方法解决了部分问题 :
article_categories = article .categories .includes(:comments => [:category_relationships]) .where(:category_relationships => {:user_id => @current_user.id})
所涉及的课程如下:
class Category :comment_relationships ... end class Comment :category_relationships ... end
上面的代码(似乎做得对):
- 通过关注
has_many :through
:category_relationships
关联(即通过关注.where(:category_relationships => {:user_id => @current_user.id})
条件)加载所有categories
; - eager加载所有
article.comments.where(:user_id => @current_user.id)
。
但是,我想补充一点:
- 按照
category_relationships
存在的:position
属性对检索到的category_relationships
进行排序,以便生成的article_categories
按位置排序 ; - 急切加载
category_relationship
对象,其中user_id == @current_user.id
因为上面的代码没有这样做。
如何利用急切的加载来实现这一目标?
解决方案:
-
.order( “category_relationships.position”)
-
想象一下,急切加载是带有一些过滤的cartessian产品,所以“where”过滤了include的最终结果(真正的左连接)。 但是它可以通过子查询来完成,子查询首先按用户过滤类别,然后可以删除。