I was recen开发者_运维百科tly 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.
The easiest way is to use a counter_cache.
Using a migration, create a comments_count:integer
database field on table posts
.
Then update your model:
class Comment < ActiveRecord::Base
belongs_to :post, :counter_cache => true
end
Then sort on that column:
Post.order(:comments_count)
One way would be a counter cache column in the case you had mentioned
post.comments_count
# instead of
post.comments.count
Not sure if that will be applicable in every of your cases.
精彩评论