我试图通过初始值设定项添加这样的范围
class ActiveRecord::Base
scope :this_month, lambda { where(:created_at => Time.now.beginning_of_month..Time.now.end_of_month) }
end
但是我收到错误"NoMethodError:对象:类的未定义方法'abstract_class?正确的方法是什么?
您正在覆盖一个类,而您应该通过模块执行此操作。我也会对这种方法有点小心,因为您正在关注每个模型都有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
这是一个工作版本,您可以包含在初始值设定项中,例如 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)