【发布时间】:2010-11-22 12:59:57
【问题描述】:
是否有向所有活动记录模型添加查找条件?
就是我想要这个查询
ExampleModel.find :all, :conditions=> ["status = ?", "active"]
表现得和
一样ExampleModel.find :all
在每个模型中
谢谢!!
【问题讨论】:
标签: ruby-on-rails activerecord find conditional-statements
是否有向所有活动记录模型添加查找条件?
就是我想要这个查询
ExampleModel.find :all, :conditions=> ["status = ?", "active"]
表现得和
一样ExampleModel.find :all
在每个模型中
谢谢!!
【问题讨论】:
标签: ruby-on-rails activerecord find conditional-statements
你可以使用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 在评论中提到的,您可能还想考虑在ActiveRecord::Base 中添加一个named_scope,命名为active,例如:
class ActiveRecord::Base
named_scope :active, :conditions => ["status = ?", "active"]
end
class ExampleModel < ActiveRecord::Base
end
ExampleModel.active # Return all active items.
【讨论】:
更新: named_scope 在 Rails 3.1 中是 deprecated/renamed。从 3.2.8 开始,新方法称为 @987654322@,它使用 where 方法而不是 :conditions
旧:
named_scope :active, :conditions => ["status = ?", "active"]
新:
scope :active, where(:status => "active")
或
scope :active, where("status = ?", "active")
【讨论】: