Adding a Search Condition for All Active Record Models in Rails

Can I add a search term for all Active record models?

then I would like this request

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

behave just like

 ExampleModel.find :all 

in each model

Thanks!!

+6
ruby-on-rails activerecord find condition
source share
2 answers

You can 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 , or get it in all your models (it may not work with single-table inheritance):

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

... or you can set default_scope to ActiveRecord::Base yourself (it can be unpleasant if you decide that one model should not have this area by default):

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

As mentioned in the klochner comments, you can also consider adding named_scope to ActiveRecord::Base called active , for example:

 class ActiveRecord::Base named_scope :active, :conditions => ["status = ?", "active"] end class ExampleModel < ActiveRecord::Base end ExampleModel.active # Return all active items. 
+17
source share

Update: named_scope been deprecated / renamed in Rails 3.1. Starting with 3.2.8, a 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") 
0
source share

All Articles