ruby-on-rails – 在Rails中为所有活动记录模型添加查找条件
发布时间:2020-12-16 21:18:08 所属栏目:百科 来源:网络整理
导读:反正有没有为所有Active记录模型添加查找条件? 这是我想要这个查询 ExampleModel.find :all,:conditions= ["status = ?","active"] 表现得和…一样 ExampleModel.find :all 在每个模型中 谢谢!! 解决方法 你可以使用 default_scope : class ExampleModel
反正有没有为所有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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |