反正有没有为所有Active记录模型添加查找条件?
这是我想要这个查询
ExampleModel.find :all,:conditions=> ["status = ?","active"]
表现得和…一样
ExampleModel.find :all
在每个模型中
谢谢!!
解决方法
你可以使用
default_scope
:
class ExampleModel < ActiveRecord::Base default_scope :conditions => ["status = ?","active"] end
如果要在所有模型中使用它,可以将ActiveRecord :: Base子类化,并从所有模型中派生出来(可能不适用于单表继承):
class MyModel < ActiveRecord::Base default_scope :conditions => ["status = ?","active"] end class ExampleModel < MyModel end
…或者您可以在ActiveRecord :: Base本身上设置default_scope(如果您确定一个模型不应该具有此默认范围,则可能会很烦人):
class ActiveRecord::Base default_scope :conditions => ["status = ?","active"] end class ExampleModel < ActiveRecord::Base end
正如klochner在评论中所提到的,您可能还想考虑将named_scope添加到ActiveRecord :: Base,名为active,例如:
class ActiveRecord::Base named_scope :active,:conditions => ["status = ?","active"] end class ExampleModel < ActiveRecord::Base end ExampleModel.active # Return all active items.