Rails has_many association count child rows

前端 未结 5 564
误落风尘
误落风尘 2020-12-13 14:07

What is the \"rails way\" to efficiently grab all rows of a parent table along with a count of the number of children each row has?

I don\'t want to use counte

5条回答
  •  一生所求
    2020-12-13 14:27

    Rails 3 Version

    For Rails 3, you'd be looking at something like this:

    Article.select( "articles.*, count(comments.id) AS comments_count" )
      .joins( "LEFT OUTER JOIN comments ON comments.article_id = articles.id" )
      .group( "articles.id" )
    

    Thanks to Gdeglin for the Rails 2 version.

提交回复
热议问题