rails named_scope作为AR :: Base的扩展

时间:2010-05-18 14:13:14

标签: ruby-on-rails named-scope extending-classes

class SomeModel < ActiveRecord::Base
  named_scope :recent, lambda { { :conditions => ['created_at > ?', 1.week.ago] } }
end

我想扩展AR :: Base类以便为所有模型使用这个named_scope,我该怎么做?

1 个答案:

答案 0 :(得分:3)

config / initializers 中创建一个新的初始化文件,然后重新打开ActiveRecord的Base类以添加命名范围:

module ActiveRecord
  class Base
    named_scope :recent, lambda {
      { :conditions => ['created_at > ?', 1.week.ago] }
    } 
  end
end

- 当然,如果您尝试在没有created_at属性的模型上使用此命名范围,则会出现相当难看的错误...