Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding find condition to all Active Record Models in Rails

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!!

like image 582
stellard Avatar asked Aug 25 '09 08:08

stellard


1 Answers

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.
like image 66
molf Avatar answered Sep 20 '22 00:09

molf