I was recently following http://railscasts.com/episodes/228-sortable-table-columns to add sortable table columns to my app. It worked great, but some of the columns in my table are things like post.comments.count (obviously posts have many comments). I’d like to be able to sort by the number of comments a post has in the table, but I can’t figure out how I’d implement this using the solution in the railscast.
I was recently following http://railscasts.com/episodes/228-sortable-table-columns to add sortable table columns to my app. It
Share
The easiest way is to use a counter_cache.
Using a migration, create a
comments_count:integerdatabase field on tableposts.Then update your model:
Then sort on that column: