3

I've tried to add a scope like this, via an initializer

class ActiveRecord::Base        
  scope :this_month,  lambda { where(:created_at => Time.now.beginning_of_month..Time.now.end_of_month) }
end

But Im getting the error "NoMethodError: undefined method `abstract_class?' for Object:Class". What is the proper way to do this?

pixelearth
  • 13,674
  • 10
  • 62
  • 110

2 Answers2

0

You are overriding a class while you should be doing it through the module. I would also be a bit careful with this approach since you are reling on every model having created_at

module ActiveRecord
  class Base
    scope :this_month,  lambda { where(:created_at => Time.now.beginning_of_month..Time.now.end_of_month) }
  end
end
Yuriy Goldshtrakh
  • 2,014
  • 1
  • 11
  • 7
0

Here is a working version you can include in a initializer like app/initializer/active_record_scopes_extension.rb.

And just call MyModel.created(DateTime.now) or MyModel.updated(3.days.ago).

module Scopes
  def self.included(base)
    base.class_eval do
      def self.created(date_start, date_end = nil)
          if date_start && date_end
            scoped(:conditions => ["#{table_name}.created_at >= ? AND #{table_name}.created_at <= ?", date_start, date_end])
          elsif date_start
            scoped(:conditions => ["#{table_name}.created_at >= ?", date_start])
          end
      end
      def self.updated(date_start, date_end = nil)
          if date_start && date_end
            scoped(:conditions => ["#{table_name}.updated_at >= ? AND #{table_name}.updated_at <= ?", date_start, date_end])
          elsif date_start
            scoped(:conditions => ["#{table_name}.updated_at >= ?", date_start])
          end
      end
    end
  end
end

ActiveRecord::Base.send(:include, Scopes)
Quentin Rousseau
  • 330
  • 5
  • 13