2012-05-01 73 views
3

我已經嘗試添加這樣的範圍內,通過初始化通過初始化程序向ActiveRecord :: Base添加作用域?

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

但是我得到的錯誤「NoMethodError:未定義的方法`abstract_class」對象:類「。什麼是正確的方法來做到這一點?

回答

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 
+2

這並沒有解決這個問題。同樣的錯誤。 – pixelearth

+0

如果您發佈了實際的初始化程序代碼以及文件的位置,這將會很有幫助。 –

0

這裏是一個工作版本,你可以包括在像app/initializer/active_record_scopes_extension.rb一個初始化每個模型reling。

並且只需致電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) 
相關問題