2011-08-28 11 views
7

रेल 3 में, मैं मॉडल में एक ही स्कोप बना देता हूं। उदाहरण के लिएक्या मैं रेल में मॉड्यूल के साथ सामान्य ActiveRecord scopes (स्कोप) का उपयोग कर सकता हूं?

class Common < ActiveRecord::Base 
    scope :recent , order('created_at DESC') 
    scope :before_at , lambda{|at| where("created_at < ?" , at) } 
    scope :after_at , lambda{|at| where("created_at > ?" , at) } 
end 

मैं सामान्य स्कॉप्स को lib में मॉड्यूल में विभाजित करना चाहता हूं। तो मैं इस तरह की कोशिश करता हूँ।

module ScopeExtension 
    module Timestamps 
    def self.included(base) 
     base.send :extend, ClassMethods 
    end 

    module ClassMethods 
     scope :recent  , lambda{order('created_at DESC')} 
     scope :before_at , lambda{|at| where("created_at < ?" , at) } 
     scope :after_at , lambda{|at| where("created_at > ?" , at) } 
    end 
end 

और मैं इस एक

class Common < ActiveRecord::Base 
    include ScopeExtension::Timestamps 
end 

लिखने लेकिन रेल इस त्रुटि को दिखाते हैं।

undefined method `scope' for ScopeExtension::Timestamps::ClassMethods:Module 

(मैं ऑटो लाइब्रेरी लोड करने भूल नहीं किया था) कैसे मैं आसानी से सक्रिय रिकॉर्ड में आम गुंजाइश सुविधा का पुन: उपयोग कर सकते हैं?

मुझे लगता है कि लोडिंग अनुक्रम से संबंधित यह समस्या है। लेकिन मुझे हल करने का कोई विचार नहीं है। कृपया मुझे संकेत दें।

उत्तर

8

मैं इस self.included (वर्ग) पर गुंजाइश बुला हल:

module Timestamps 
    def self.included(k) 
     k.scope :created_yesterday, k.where("created_at" => Date.yesterday.beginning_of_day..Date.yesterday.end_of_day) 
     k.scope :updated_yesterday, k.where("created_at" => Date.today.beginning_of_day..Date.today.end_of_day) 
     k.scope :created_today, k.where("created_at" => Date.today.beginning_of_day..Date.today.end_of_day) 
     k.scope :updated_today, k.where("created_at" => Date.today.beginning_of_day..Date.today.end_of_day) 
    end 
end 
6

रेल 3 में एक घोषित गुंजाइश और एक वर्ग विधि है कि एक ActiveRecord::Relation रिटर्न के बीच कोई अंतर नहीं है, तो यह और अधिक सुरुचिपूर्ण हो सकता है एक मिश्रण मॉड्यूल का उपयोग करने के लिए:

class MyClass < ActiveRecord::Base 
    extend ScopeExtension::Timestamps 
end 

module ScopeExtension 
    module Timestamps 
    def recent 
     order('created_at DESC') 
    end 

    def before_at(at) 
     where('created_at < ?' , at) 
    end 

    def after_at(at) 
     where('created_at > ?' , at) 
    end 
    end 
end 

MyClass.after_at(2.days.ago).before_at(1.hour.ago).recent 
संबंधित मुद्दे