Adding scope to ActiveRecord :: Base through an initializer?

I tried to add an area like this through the 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 right way to do this?

+3
source share
2 answers

You redefine the class while you have to do it through the module. I would also be a little cautious with this approach, since you relate to each model with create_at

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

Here is a working version that you can enable in the initializer, for example 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)
0
source

All Articles