Adding find condition to all Active Record Models in Rails

萝らか妹 提交于 2019-12-21 04:55:08

问题


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


回答1:


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.



回答2:


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")


来源:https://stackoverflow.com/questions/1326743/adding-find-condition-to-all-active-record-models-in-rails

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