I am trying to show into article#index how many comments where on each articles.
So i have the following models
resources Article do
resources Comments do
end
end
I know in each article I can do the follow and this would work:
@count = @article.comments.find(:all).count
And just show in the view count. But then problem comes when i am in an index file and not sure how to show how many comments exist for this event atm.
Thanks in advance
articles_controller.rb
articles/index.html.erb
The nested routes (comments within articles) matters more in terms of your create/destroy routes for comments. Also be sure to add
accepts_nested_attributes_for :commentsin your Article model. This will allow you to do stuff like this:for example, in articles_controller.rb
Edit
If you do start caring about performance, I agree with Kitto’s comment.
Add this migration:
And change your relation declaration in your Comment model to this:
Then you can make calls like this
article.comments_countto get the count instead ofatricle.comments.count. And it’s great if the count is 0, because it doesn’t even make the query (p. 195 of The Rails 3 Way).If you’re curious about how counter_cache works: it adds a callback to the belonging class (in this case, the Comment class) that updates the comments_counter attribute on the parent article each time a comment is created or destroyed.
Also, counter_cache functionality can easily be added to existing databases as demonstrated here, by Obie Fernandez.