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.