【发布时间】:2010-09-09 23:22:50
【问题描述】:
我有几个模型需要自定义查找条件。例如,如果我有一个 Contact 模型,每次调用 Contact.find 时,我都想限制返回的联系人仅属于正在使用的 Account。
我通过谷歌找到了这个(我已经定制了一点):
def self.find(*args)
with_scope(:find => { :conditions => "account_id = #{$account.id}" }) do
super(*args)
end
end
这很好用,除了 account_id 不明确的少数情况,因此我将其调整为:
def self.find(*args)
with_scope(:find => { :conditions => "#{self.to_s.downcase.pluralize}.account_id = #{$account.id}" }) do
super(*args)
end
end
这也很好用,但是,我希望它是干燥的。现在我有几个不同的模型,我希望使用这种功能。最好的方法是什么?
当您回答时,请附上代码以帮助我们的头脑掌握元编程 Ruby-fu。
(我使用的是 Rails v2.1)
【问题讨论】:
标签: ruby-on-rails ruby activerecord metaprogramming overriding