Adding find condition to all Active Record Models in Rails
-
19-09-2019 - |
Question
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!!
Solution
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.
OTHER TIPS
Update: named_scope
was deprecated/renamed in Rails 3.1. As of 3.2.8, the new method is called scope
which uses the where
method instead of :conditions
Old:
named_scope :active, :conditions => ["status = ?", "active"]
New:
scope :active, where(:status => "active")
or
scope :active, where("status = ?", "active")