Rails4范围或条件具有新语法

时间:2014-05-19 10:18:12

标签: ruby-on-rails ruby-on-rails-4

所以我有这个工作范围(我使用的是rails4):

scope :closed, where("state=? OR state=?", 'pending', 'complete')

但是,铁路投诉:

DEPRECATION WARNING: Using #scope without passing a callable object is deprecated. For example `scope :red, where(color: 'red')` should be changed to `scope :red, -> { where(color: 'red') }`. There are numerous gotchas in the former usage and it makes the implementation more complicated and buggy. (If you prefer, you can just define a class method named `self.red`.).

但是,我找不到使用OR条件的推荐语法的方法。正如建议所说,有没有办法优雅地做到这一点? 感谢

3 个答案:

答案 0 :(得分:1)

从新语法格式开始,我们需要指定lambda块符号( - >),因此将来的版本中将删除这种旧格式。所以你的范围将变成这样的,

scope, :closed, -> { where('state = ? OR state = ?', 'pending', 'complete') }

答案 1 :(得分:0)

你应该简单地使用lambda:

scope :closed, -> { where('state = ? OR state = ?', 'pending', 'complete') }

答案 2 :(得分:0)

范围(名称,正文和阻止)

添加用于检索和查询对象的类方法。范围表示缩小数据库查询。

scope :closed, -> { where('state = ? OR state = ?', 'pending', 'complete') }

有关详细信息,请参阅 Ruby Doc