我正在运行 Ruby on Rails 3.1。我想通过应用一些条件来加载“二级”关联对象,但我遇到了麻烦。
看来我已经解决了我的问题的一部分通过使用:
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
上面的代码(看起来是正确的):
- 加载全部
categories
通过关心has_many :through
:category_relationships
协会(即通过关心.where(:category_relationships => {:user_id => @current_user.id})
健康)状况);
- 急切加载所有
article.comments.where(:user_id => @current_user.id)
.
不过,我还想多说一些:
- to order检索到的
categories
by a :position
属性存在于category_relationships
使得由此产生的article_categories
are 按位置排序;
- to 急切加载 also
category_relationship
物体在哪里user_id == @current_user.id
因为上面的代码没有做到这一点。
我如何利用急切加载来实现这一点?
解决方案:
.order("category_relationships.position")
想象一下急切加载是带有一些过滤的笛卡尔积,因此“where”正在过滤包含的最终结果(实际上是左连接)。但这可以用where
使用子查询,首先将按用户过滤类别,然后可以删除您的位置。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)