Adding find condition to all Active Record Models in Rails

蓝咒 提交于 2019-12-03 15:10:20

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.

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")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!