RoR - How To Count & Display Comments [closed]
I'm looking to have a count of the number of comments left under an article and display it on the index page beside that particular article - like the example here in red circles. Any suggestions as to how I might do this?
The picture is an example of what I'm trying to do, its not my site.
This sounds like a good candidate for Rails.cache
. Every time you create a new comment simply increment that cache counter using the post id.
If the cache entry does not exist, do a simple article.comments.count
(depends on your domain model of course) query and re-cache it.
Storing it in a cache is one idea, yes.
But storing it in a counter_cache
column is probably a better idea. That way even if your server was restarted somehow you wouldn't loose the cached values. See http://guides.rubyonrails.org/association_basics.html, section 4.1.2.4.
精彩评论