I have a few models that need to have custom find conditions placed on them. For example, if I have a Contact model, every time Contact.find is called, I want to restrict the contacts returned that only belong to the Account in use.
I found this via Google (which I've customized a little):
def self.find(*args)
with_scope(:find => { :conditions => "account_id = #{$account.id}" }) do
super(*args)
end
end
This works great, except for a few occasions where account_id is ambiguous so I adapted it to:
def self.find(*args)
with_scope(:find => { :conditions => "#{self.to_s.downcase.pluralize}.account_id = #{$account.id}" }) do
super(*args)
end
end
This also works great, however, I want it to be DRY. Now I have a few different models that I want this kind of function to be used. What is the best way to do this?
When you answer, please include the code to help our minds grasp the metaprogramming Ruby-fu.
(I'm using Rails v2.1)