2009-08-25 31 views

回答

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,你可能还需要考虑增加一个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. 
+0

如何关于ActiveRecord :: Base的命名范围?如果项目得到共享,那么混淆其他开发者的可能性就会降低。 – klochner 2009-08-25 16:14:45

+0

@ klochner,是的,好点。使用像ExampleModel.active这样的东西非常有表现力。 – molf 2009-08-25 16:23:24

+0

来清理它多一点,你可以从ActiveRecord派生一个具有命名(或新的默认)作用域的类,并从中派生出ExampleModel。现在新功能是明确的。 – klochner 2009-08-25 19:26:40

0

更新:named_scope是Rails的3.1 deprecated/renamed。截至3.2.8,新方法被称为scope它使用where方法,而不是:conditions

老:

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

新:

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

scope :active, where("status = ?", "active") 
相关问题