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。
任何想法?任何幫助讚賞。
是的,這將是一個很好的創造性的解決方案。這不是一個混合? –
是的。這是標準技術 – woto