急切加载“二级”关联对象时出现问题
Posted
技术标签:
【中文标题】急切加载“二级”关联对象时出现问题【英文标题】:Trouble on eager loading "second degree" associated objects 【发布时间】:2012-03-26 15:44:54 【问题描述】:我正在运行 Ruby on Rails 3.1。我想通过应用一些条件来急切地加载“二级”关联对象,但我遇到了麻烦。
看来我已经通过使用解决了part of my issue:
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
上面的代码(好像做对了):
-
通过关注
has_many :through
:category_relationships
关联(即通过关注.where(:category_relationships => :user_id => @current_user.id)
条件)加载所有categories
;
渴望加载所有article.comments.where(:user_id => @current_user.id)
。
不过,我想多做一些:
-
to order 通过
category_relationships
中存在的:position
属性检索categories
,以便生成的article_categories
按位置排序;
到急切加载还有category_relationship
对象user_id == @current_user.id
,因为上面的代码没有做到这一点。
如何利用即时加载来实现这一点?
【问题讨论】:
您在Category
和Comment
之间使用两个不同的连接表有什么原因吗?
【参考方案1】:
解决办法:
.order("category_relationships.position")
想象急切加载是带有一些过滤的笛卡尔积,因此“where”正在过滤包含的最终结果(实际上是左连接)。但是可以使用带有子查询的where
来完成,该子查询首先会按用户过滤类别,然后可以删除您的位置。
【讨论】:
你能举个例子吗?以上是关于急切加载“二级”关联对象时出现问题的主要内容,如果未能解决你的问题,请参考以下文章