急于加载“二度”关联对象的麻烦

我正在运行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 

上面的代码(似乎做得对):

  1. 通过关注has_many :through :category_relationships关联(即通过关注.where(:category_relationships => {:user_id => @current_user.id})条件)加载所有categories ;
  2. eager加载所有article.comments.where(:user_id => @current_user.id)

但是,我想补充一点:

  1. 按照 category_relationships存在的:position属性对检索到的category_relationships进行排序,以便生成的article_categories 按位置排序 ;
  2. 急切加载 category_relationship对象,其中user_id == @current_user.id因为上面的代码没有这样做。

如何利用急切的加载来实现这一目标?

解决方案:

  1. .order( “category_relationships.position”)

  2. 想象一下,急切加载是带有一些过滤的cartessian产品,所以“where”过滤了include的最终结果(真正的左连接)。 但是它可以通过子查询来完成,子查询首先按用户过滤类别,然后可以删除。