Rails has_many association count child rows

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

    A simple way that I used to solve this problem was

    In my model I did:

    class Article < ActiveRecord::Base
      has_many :posts
    
      def count_posts
        Post.where(:article_id => self.id).count
      end
    end
    

    Now, you can use for example:

    Articles.first.count_posts
    

    Im not sure if it can be more efficient way, But its a solution and in my opinion more elegant than the others.

提交回复
热议问题