急于加载和使用“ where”方法的问题 [英] Trouble on eager loading and using the 'where' method

查看:66
本文介绍了急于加载和使用“ where”方法的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行Ruby on Rails 3.1。我正在使用 includes 方法,我想了解为什么在急切加载的集合中调用 where 方法时的原因它会重新加载关联的对象,而不仅仅是在渴望加载的集合中找到该对象。因为所有相关对象都已经被加载,所以我希望 where 方法不会命中数据库以重新加载那些对象!

I am running Ruby on Rails 3.1. I am using the includes method and I would like to understand why when I call the where method on an eager loaded collection it reloads associated objects instead of just finding that object in the eager loaded collection. Since all related objects are already been eager loaded I expect that the where method does not hit the database to reload those objects!

也就是说,我有以下内容:

That is, I have the following:

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 的注释标题,但我不想检索

eager loading works as expected: the "N + 1 query problem" is avoided. However, the above code returns also comment titles that have not ":user_id == @current_user.id", but I do not want to retrieve those ones at all.

因此,由于我认为通过急切的加载,我已经获得了所有注释,因此我又使用了 where(: user_id => @ current_user.id)语句,如以下代码所示:

So, since I thought that by using the eager loading I already get all comments, I used a further where(:user_id => @current_user.id) statement like in the following code:

# CASE 2:

article_categories.each do |article_category|
  article_category.comments.where(:user_id => @current_user.id).map(&:title)
end

但是,在这种情况下,紧急加载不能按预期的方式工作: 1个查询问题...但是注释中包含 :user_id == @ current_user.id

However, in this case eager loading does not work as expected: the "N + 1 query problem" is not avoided... but comments have ":user_id == @current_user.id"!

我会想急于使用 :user_id == @ current_user.id 来加载评论(如何利用急切的加载来做到这一点? ),我想了解为什么 where 语句取消了急切的加载效果。

I would like to eager loading comments with ":user_id == @current_user.id" (how can I make that by taking advantage from the eager loading?) and I would like to understand why the where statement cancels eager loading effects.

推荐答案

在情况1中,where子句仅适用于类别。如果还希望将其应用于评论,则可以执行以下操作:

In case 1 the where clause only applies to categories. If you also want it to apply to comments you can do this:

article_categories =
  article
    .categories
    .includes(:comments)
    .where('categories.user_id = ? AND comments.user_id = ?', @current_user.id, @current_user.id)

这篇关于急于加载和使用“ where”方法的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆