I have two models
Post
has_many :comments
Comment
belongs_to :post
When I want display a list of posts and it’s comment count. I usually include comments in the post like this .
Post.find(:all,:include => :comments)
To display a number of comment for post.
post.comments.size
Can I create a has_many relation which return count of comments ?
has_one :comments_count
Can I include this relationship like this ?
Post.find(:all,:include => :comments_count)
Rails has a counter cache which will automatically update a columns value based on the count of associated items. This will allow you to include the count when you return the posts object. Just add it to the belongs_to on comment.
You’ll need to add a new integer column to posts for the counter: