Applying default conditions to a model's find, find_by_*


#1

What is the best solution for applying a default condition to a model,
for example only records where active is boolean true? My initial
implementation overrode the find method using with_scope to apply the
condition, but I soon discovered that didn’t work with the
will_paginate plugin.

I currently have a named_scope called :active that applies the
conditions, but I’m not sure how to incorporate that so that it is
always applied to find and find_by_* without having to use it inside
of the controller.

I’d also like to apply a default sort order and have this code. Could
I follow similar logic for applying the condition?

def self.find(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
if not options.include? :order
options[:order] = ‘created_at desc’
end
args.push(options)
super
end


#2

If you can move to Rails 2.3, which is currently in release candidate
testing, you could use default scoping:
http://ryandaigle.com/articles/2008/11/18/what-s-new-in-edge-rails-default-scoping

Regards,
Craig


#3

Not at this point, so I’d prefer to come up with a solution using
2.2.2.


#4

I originally used a with_scope, but that doesn’t play nicely with
will_paginate.

On Feb 27, 3:14 pm, Maurício Linhares removed_email_address@domain.invalid


#5

At your model, override the find method:

class SomeModel < ActiveRecord::Base

class << self

def find(*args)
  with_scope( :conditions => {:property => 'value'} ) do
    super(*args)
  end
end

end

end

Maurício Linhares
http://alinhavado.wordpress.com/ (pt-br) | http://blog.codevader.com/
(en)