通过初始化程序向ActiveRecord :: Base添加范围?

时间:2012-05-01 18:55:57

标签: ruby-on-rails activerecord initializer scoping

我试图通过初始化程序

添加这样的范围
class ActiveRecord::Base        
  scope :this_month,  lambda { where(:created_at => Time.now.beginning_of_month..Time.now.end_of_month) }
end

但我得到错误“NoMethodError:undefined method`abstract_class?' for Object:Class“。这样做的正确方法是什么?

2 个答案:

答案 0 :(得分:0)

你应该通过模块覆盖课程。 我对这种方法也会有点小心,因为你正在使用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

答案 1 :(得分:0)

以下是可以包含在app/initializer/active_record_scopes_extension.rb等初始值设定项中的工作版本。

只需致电MyModel.created(DateTime.now)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)