Override default find conditions for model

Here is a little trick I use when I want to override a find method for a model, instead of adding the conditions option to my association. While I don’t think you should avoid using the conditions options in your associations, this will provide an alternative:

class ModelName < ActiveRecord::Base
  def self.find(*args)
    with_scope(:find=>{ :conditions=>LIMIT_CONDITION }) do
      super(*args)
    end
  end
end

Basically what is happening, is that you are overriding the default find function for a model, and wrapping its own find method with a with_scope call. So now every time you call Model.find(:all) or whatever options you want, it will execute it under that scope, with the conditions you specify.

2 thoughts on “Override default find conditions for model

  1. What if you want to do for all the models i.e. for ActiveRecord::Base ??

    Also, this does not work with associations.

    So @blog.posts.find will still not retrieve only non-deleted posts even if above method is defined in posts model. How can we get over this ?

    I will appreciate if you could please mail me the solution 🙂

  2. Thanks. Just what I was looking for.

    To answer AJ (a little late I know), you want to open up ActiveRecord::Base class (create a file in lib or an initializer then just do class ActiveRecord::Base) and alias the find method then use the code above and call the aliased method instead of super.

    As for non-deleted in the example above you could just call ActiveRecord::Base.find directly but if you’ve aliased the method you’ll want to call that instead.

Leave a Reply

Your email address will not be published. Required fields are marked *