Trouble on eager loading and using the 'where' method

旧街凉风 提交于 2019-12-11 04:54:14

问题


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)

If I run

# CASE 1:

article_categories.each do |article_category|
  article_category.comments.map(&:title)
end

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.

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

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"!

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:


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)


来源:https://stackoverflow.com/questions/9629046/trouble-on-eager-loading-and-using-the-where-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!