添加查找条件在Rails的所有活动记录模式(Adding find condition to all

2019-08-02 10:12发布

反正是有一个查找条件添加到所有活动记录模式?

这是我想这个查询

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

表现方法一样

ExampleModel.find :all

在每一个模型

谢谢!!

Answer 1:

你可以使用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

...或者你可以设置default_scopeActiveRecord::Base本身(如果您认为一个模型不应该有此默认范围可能是恼人的):

class ActiveRecord::Base
  default_scope :conditions => ["status = ?", "active"]
end
class ExampleModel < ActiveRecord::Base
end

正如在评论klochner提到的,你可能还需要考虑增加一个named_scopeActiveRecord::Base ,名为active ,例如:

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


Answer 2:

更新: 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")


文章来源: Adding find condition to all Active Record Models in Rails