Eager-loading association count with Arel (Rails 3)

纵然是瞬间 提交于 2020-01-04 02:55:26

问题


Simple task: given that an article has many comments, be able to display in a long list of articles how many comments each article has. I'm trying to work out how to preload this data with Arel.

The "Complex Aggregations" section of the README file seems to discuss that type of situation, but it doesn't exactly offer sample code, nor does it offer a way to do it in two queries instead of one joined 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 for an article set how many comments each has?


回答1:


You can do something nasty using SQL like:

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

and then you would have access to Article.first.count_comments.

Another (nicer) method to do it is to use the 'counter_cache' feature/option from belongs_to association.




回答2:


Can't you use counter cache for this?

belongs_to :article, :counter_cache => true

You also need to have a migration that adds the column comments_count



来源:https://stackoverflow.com/questions/2596783/eager-loading-association-count-with-arel-rails-3

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