开发者

rails named_scope as an extension to AR::Base

开发者 https://www.devze.com 2022-12-30 12:33 出处:网络
class SomeModel < ActiveRecord::Ba开发者_如何学Cse named_scope :recent, lambda { { :conditions => [\'created_at > ?\', 1.week.ago] } }
class SomeModel < ActiveRecord::Ba开发者_如何学Cse
  named_scope :recent, lambda { { :conditions => ['created_at > ?', 1.week.ago] } }
end

I want to extend the AR::Base class to have this named_scope for all models, how I can do this ?


Create a new initializer file in config/initializers and then re-open ActiveRecord's Base class to add the named scope:

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

—Of course you get a rather ugly error should you attempt to use this named scope on a model that doesn't have a created_at attribute...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号