views:

1046

answers:

1

Is there anyway to add a find condition to all Active record models?

that is I would like this query

ExampleModel.find :all, :conditions=> ["status = ?", "active"]

to behave the same way as

ExampleModel.find :all

in every model

Thanks!!

+8  A: 

You could use default_scope:

class ExampleModel < ActiveRecord::Base
  default_scope :conditions => ["status = ?", "active"]
end

If you want to use this in all your models, you can either subclass ActiveRecord::Base and derive from that in all your models (probably doesn't work well with single-table inheritance):

class MyModel < ActiveRecord::Base
  default_scope :conditions => ["status = ?", "active"]
end
class ExampleModel < MyModel
end

...or you could set the default_scope on ActiveRecord::Base itself (could be annoying if you decide that one model should not have this default scope):

class ActiveRecord::Base
  default_scope :conditions => ["status = ?", "active"]
end
class ExampleModel < ActiveRecord::Base
end

As mentioned by klochner in a comment, you may also want to consider adding a named_scope to ActiveRecord::Base, named active, for example:

class ActiveRecord::Base
  named_scope :active, :conditions => ["status = ?", "active"]
end
class ExampleModel < ActiveRecord::Base
end
ExampleModel.active  # Return all active items.
molf
how about a named scope on ActiveRecord::Base? That would be less likely to confuse other developers if the project gets shared.
klochner
@klochner, yes, good point. Using something like ExampleModel.active is very expressive.
molf
to clean it up a little more, you could derive a class from ActiveRecord that has the named (or new default) scope, and have ExampleModel derive from that. Now the new functionality is explicit.
klochner
Great. Thanks for the answer. One more question though. How can I use this named route while still allowing for adding more conditions to the search?
rube_noob
@rube_noob: You can chain the named scopes (any number) and the regular find methods: ExampleModel.active.find(:conditions => ...).
molf