在Rails中为所有Active Record模型添加查找条件

6

有没有办法将查找条件添加到所有Active record模型中?

也就是说,我想要这个查询:

ExampleModel.find :all, :conditions=> ["status = ?", "active"]

表现出与...相同的行为

ExampleModel.find :all

在每个模型中

谢谢!

2个回答

17

您可以使用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添加一个名为activenamed_scope

class ActiveRecord::Base
  named_scope :active, :conditions => ["status = ?", "active"]
end
class ExampleModel < ActiveRecord::Base
end
ExampleModel.active  # Return all active items.

如何在ActiveRecord :: Base上使用命名作用域? 这将减少在共享项目时混淆其他开发人员的可能性。 - klochner
@klochner,是的,很好的观点。使用类似ExampleModel.active这样的东西非常具有表现力。 - molf
为了更好地整理代码,您可以从ActiveRecord派生一个类,该类具有命名(或新默认)范围,并使ExampleModel从该类派生。现在,新功能是显式的。 - klochner
太好了,谢谢你的回答。不过我还有一个问题。我如何在保留添加更多搜索条件的同时使用这个命名路由? - stellard
@rube_noob:你可以链式调用命名作用域(任意数量)和常规的查找方法:ExampleModel.active.find(:conditions => ...)。 - molf

0

更新:named_scope在Rails 3.1中已被弃用/更名。从3.2.8开始,新的方法称为scope,它使用where方法而不是:conditions

旧:

named_scope :active, :conditions => ["status = ?", "active"]

新的:

scope :active, where(:status => "active")

或者

scope :active, where("status = ?", "active")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接