【发布时间】: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之间使用两个不同的连接表有什么原因吗?
标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1 eager-loading