2011-07-20 46 views
0

在我的項目中,我有幾個模型使用了一些用於運行日常任務的作用域(請參閱下面的縮短代碼)。在rails 3.1中使用對象作用域

class Company < ActiveRecord::Base 

    def self.to_create(start_time, end_time) 
    where(active:1). 
    where("created_at between ? and ?", 
      start_time.strftime('%F %T'), 
      end_time.strftime('%F %T')) 
    end 

    def self.to_update(start_time, end_time) 
    where(active:1). 
    where("updated_at between ? and ?", 
      start_time.strftime('%F %T'), 
      end_time.strftime('%F %T')). 
    where('updated_at > active_updated_at') 
    end 

end 

class JobPosting < ActiveRecord::Base 

    def self.to_create(start_time, end_time) 
    where(active:1). 
    where("created_at between ? and ?", 
      start_time.strftime('%F %T'), 
      end_time.strftime('%F %T')) 
    end 

    def self.to_update(start_time, end_time) 
    where(active:1). 
    where("updated_at between ? and ?", 
      start_time.strftime('%F %T'), 
      end_time.strftime('%F %T')). 
    where('updated_at > active_updated_at') 
    end 

end 

顯然,範圍看起來是一樣的,我想通過重新使用範圍代碼乾涸一些代碼。我發現這篇文章:http://hemju.com/2011/02/23/rails-3-1-release-rumors-and-news-about-features/也描述了傳遞對象的範圍。因此,我決定嘗試一下。

/app/models/filter.rb

class Filter < Struct.new(:klass) 
    def call(*args); end 
end 

module ToCreateFilter 
    def call(*args) 
    start_time = args.shift 
    end_time = args.shift 
    klass.where(active:1).where("created_at between ? and ?", 
      start_time, 
      end_time) 
    super(*args) 
    end 
end 

/app/models/company.rb

class Company < ActiveRecord::Base 

    scope :to_create, Filter.new(self).extend(ToCreateFilter) 

end 

,我把它想:

Company.to_create(START_TIME,END_TIME)

然而,此範圍內無法返回正確的記錄數量(簡單地返回al l記錄在表中)。試圖追蹤錯誤的來源並沒有產生任何結果。在ToCreateFilter中使用print語句證明執行得到預期的位置並生成正確的sql。

任何想法?任何幫助讚賞。

回答

2

可以更好地定義模塊這樣

module ScopeForUser 
    def self.included(base) 
    base.class_eval { 
     # Для выборки из корзины и т.д. Другими словами где не требуется регистрация 
     scope :get_for, lambda { |user, session_id| 
     unless user.nil? 
      where(:user_id => user.id) 
     else 
      where(:session_id => session_id) 
     end 
     } 
    } 
    end 
end 

,然後簡單的將其包含在AR模型?

+0

是的,這將是一個很好的創造性的解決方案。這不是一個混合? –

+0

是的。這是標準技術 – woto