Rails 3 - default_scope
I would like to order the article tags on my index page by popularity as opposed to by creation date i.e. the tags with the most amount of articles in them from highest to lowest. My model is as follows?
class Tag < ActiveRecor开发者_Go百科d::Base
attr_accessible :name
validates :name, :uniqueness => true
# order by creation
default_scope :order => 'created_at DESC'
has_many :taggings, :dependent => :destroy
has_many :articles, :through => :taggings
end
I recommend using a counter cache column to store a taggings_count
(which automatically gets updated when new taggings).
And then your default scope can look like this:
default_scope :order => 'taggings_count DESC'
For more info, search for "counter_cache" in the Rails guide for AR associations
精彩评论