# Of download ratings from Arel (Rails 3)

A simple task: given that there are many comments in the article, you can display the number of comments of each article in a long list of articles. I am trying to figure out how to preload this data with Arel.

The Integrated Aggregations section of the README file seems to discuss this type of situation, but it certainly does not offer sample code, nor does it offer a way to do this in two queries instead of a single combined query, which is worse for performance.

Given the following:

class Article
  has_many :comments
end

class Comment
  belongs_to :article
end

How can I preload the article, how many comments do each have?

+3
source share
2

- , SQL:

default_scope :select => 'articles.*, (select count(comments.id) from comments where comments.article_id = articles.id) as count_comments'

Article.first.count_comments.

( ) / counter_cache _ .

+2

- ?

belongs_to :article, :counter_cache => true

, comments_count

+4

Source: https://habr.com/ru/post/1740239/


All Articles