2
class SomeModel < ActiveRecord::Base
  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 ?

astropanic
  • 10,800
  • 19
  • 72
  • 132

1 Answers1

3

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...

John Topley
  • 113,588
  • 46
  • 195
  • 237