【发布时间】:2012-03-26 14:35:42
【问题描述】:
我正在运行 Ruby on Rails 3.1。我正在使用includes 方法,我想了解为什么当我在急切加载的集合上调用where 方法时,它会重新加载关联的对象,而不仅仅是在急切加载的集合中找到该对象。由于所有相关对象都已预先加载,我希望 where 方法不会访问数据库以重新加载这些对象!
也就是说,我有以下内容:
article_categories =
article
.categories
.where(:user_id => @current_user.id)
.includes(:comments)
如果我跑步
# CASE 1:
article_categories.each do |article_category|
article_category.comments.map(&:title)
end
预加载按预期工作:避免了“N + 1 查询问题”。但是,上面的代码也返回了带有 not“:user_id == @current_user.id”的注释标题,但我根本不想检索那些。
因此,由于我认为通过使用预先加载我已经获得了所有 cmets,因此我使用了进一步的 where(:user_id => @current_user.id) 语句,如下面的代码:
# CASE 2:
article_categories.each do |article_category|
article_category.comments.where(:user_id => @current_user.id).map(&:title)
end
但是,在这种情况下,急切加载没有按预期工作:没有避免了“N + 1 查询问题”......但是 cmets 有“@987654329 @"!
我想使用“:user_id == @current_user.id”预加载 cmets(如何利用预加载的优势来实现这一点?)我想了解为什么 @ 987654331@ 语句取消急切加载效果。
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1 eager-loading