Rails 3 - default_scope

ubi*_*que 4 ruby-on-rails-3

我想按照受欢迎程度而不是创建日期在我的索引页面上订购文章标签,即从最高到最低的文章中包含最多文章的标签.我的模特如下?

class Tag < ActiveRecord::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
Run Code Online (Sandbox Code Playgroud)

Jit*_*its 5

我建议使用计数器缓存列来存储taggings_count(当新标记时自动更新).

然后您的默认范围可能如下所示:

default_scope :order => 'taggings_count DESC'
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请在Rails指南中搜索AR关联的 "counter_cache"