Home>

If i have the following association model, if you narrow down the article_comments table with the where method in the loop processing, you will issue a query without using the cache and you will have an N + 1 problem.
Sorry to trouble you, but what should you do if I want to reduce the number of queries issued?

As for what I tried, I used the includes method and the eager_load method for FavoriteFeed and used the cache, but the number of queries issued did not decrease.

class Article</pre>
<pre><code>class User</pre>
<pre><code>class FavoriteFeed</pre>
<pre><code>class ArticleComment</pre>
<p>Processing for issuing N queries</p>
<pre><code>FavoriteFeed.eager_load (article :: article_comments) .each do | feed |
 puts "article name: # {feed.name}"
 article.article_comments.where (user_id: [1, 2]). each do | article_comment |
  puts "article comment: # {article_comment.comment}"
 end
end
  • Answer # 1

    .whereMeans "pull the table to narrow down", so issue a query when you use it.

    Simplyeager_loadAfter applyingEnumerableIt is conceivable to narrow down as.

    article.article_comments.select {| item | item.user_id.in? [1, 2]} .each do | article_comment |

Related articles