向 Rails 中的所有 Active Record 模型添加查找条件 [英] Adding find condition to all Active Record Models in Rails
问题描述
是否有向所有活动记录模型添加查找条件?
Is there anyway to add a find condition to all Active record models?
就是我想要这个查询
ExampleModel.find :all, :conditions=> ["status = ?", "active"]
表现得和
ExampleModel.find :all
在每个模型中
谢谢!!
推荐答案
你可以使用 default_scope
:
You could use default_scope
:
class ExampleModel < ActiveRecord::Base
default_scope :conditions => ["status = ?", "active"]
end
如果您想在所有模型中使用它,您可以继承 ActiveRecord::Base
并在所有模型中派生它(可能不适用于单表继承):
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
...或者您可以在 ActiveRecord::Base
本身上设置 default_scope
(如果您决定一个模型不应该具有此默认范围,可能会很烦人):
...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
正如 klochner 在评论中提到的,您可能还需要考虑将 named_scope
添加到 ActiveRecord::Base
,命名为 active
,例如:
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.
这篇关于向 Rails 中的所有 Active Record 模型添加查找条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!