Rails has_many association count child rows

前端 未结 5 574
误落风尘
误落风尘 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:30

    This activerecord call should do what you want:

    Article.find(:all, :select => 'articles.*, count(posts.id) as post_count',
                 :joins => 'left outer join posts on posts.article_id = articles.id',
                 :group => 'articles.id'
                )
    

    This will return a list of article objects, each of which has the method post_count on it that contains the number of posts on the article as a string.

    The method executes sql similar to the following:

    SELECT articles.*, count(posts.id) AS post_count
    FROM `articles`
    LEFT OUTER JOIN posts ON posts.article_id = articles.id
    GROUP BY articles.id
    

    If you're curious, this is a sample of the MySQL results you might see from running such a query:

    +----+----------------+------------+
    | id | text           | post_count |
    +----+----------------+------------+
    |  1 | TEXT TEXT TEXT |          1 |
    |  2 | TEXT TEXT TEXT |          3 |
    |  3 | TEXT TEXT TEXT |          0 |
    +----+----------------+------------+
    

提交回复
热议问题