将查找条件添加到Rails中的所有活动记录模型
反正有没有为所有Active记录模型添加查找条件?
这是我想要这个查询
ExampleModel.find :all, :conditions=> ["status = ?", "active"]
表现得和…一样
ExampleModel.find :all
在每个模型中
谢谢!!
你可以使用default_scope
:
class ExampleModel < ActiveRecord::Base default_scope :conditions => ["status = ?", "active"] end
如果要在所有模型中使用它,可以将ActiveRecord::Base
子类化,并从所有模型中派生出来(可能不适用于单表inheritance):
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.
更新:在Rails 3.1中不推荐/重命名了named_scope
。 从3.2.8开始,新方法称为scope
,它使用where
方法而不是:conditions
旧:
named_scope :active, :conditions => ["status = ?", "active"]
新:
scope :active, where(:status => "active")
要么
scope :active, where("status = ?", "active")
- 创建schema_migrations的Rails – Mysql2 ::错误:指定的键太长了
- 在Rails 3中禁用BLOB日志记录
- validation和更新单个属性rails
- 如何在Rails中使用Active Record时指定Ruby正则表达式?
- 在Ruby on Rails 3中制作通用模型时出现的问题
- Rails 4嵌套属性和has_many:通过表单中的associaton
- Rails 4 x paper_trail:使用嵌套资源按item_id过滤版本
- ActiveRecord并使用reject方法
- 为什么ActiveRecord :: StatementInvalid:SQLite3 :: SQLException:near“)”:语法错误:INSERT INTO“user_friendships”()VALUES()