【问题标题】:adding a scope to ActiveRecord::Base via initializer?通过初始化程序向 ActiveRecord::Base 添加范围?
【发布时间】:2012-05-11 06:33:55
【问题描述】:

我尝试通过初始化程序添加这样的范围

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?'对象:类”。这样做的正确方法是什么?

【问题讨论】:

    标签: ruby-on-rails activerecord initializer scoping


    【解决方案1】:

    你正在重写一个类,而你应该通过模块来做。 我也会对这种方法有点小心,因为您依赖于每个具有 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
    

    【讨论】:

    • 如果您发布了您拥有的实际初始化程序代码以及文件的位置,将会很有帮助。
    【解决方案2】:

    这是一个工作版本,您可以将其包含在 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-31
      • 1970-01-01
      • 1970-01-01
      • 2021-07-08
      • 2015-08-14
      • 1970-01-01
      • 2014-04-10
      相关资源
      最近更新 更多