【问题标题】:Rails4 scope OR condition with new syntax具有新语法的 Rails4 范围 OR 条件
【发布时间】:2014-05-19 10:18:12
【问题描述】:

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

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

但是,Rails 抱怨:

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 条件一起使用的方法。正如建议所说,有什么方法可以优雅地做到这一点? 谢谢

【问题讨论】:

  • 答案在弃用警告中
  • 问题在于使用 OR 和建议语法!我希望不在字符串中使用状态......但我知道这只是语法上的轻微变化。
  • 我不明白为什么我会在这个问题上获得如此多的反对票......所以,我应该阅读的内容是:“以前的用法有很多陷阱,它使实现更加复杂和错误。”就是这样:如果你放一个箭头和一些括号,那么实现就会少一些错误......这个想法一定比这更大。我期待一个更漂亮的解决方案,就是这样。

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


【解决方案1】:

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

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

【讨论】:

  • 我期待与此类似的东西:scope :closed, -> { where(state: 'pending').or.where(state: 'complete') } 但我发现我更复杂了,我接受你的建议。谢谢
  • 范围后面有一个多余的逗号。
【解决方案2】:

你应该简单地使用 lambda:

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

【讨论】:

    【解决方案3】:

    范围(名称、正文、&块)

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

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

    有关更多信息,请参阅此Ruby Doc

    【讨论】:

      猜你喜欢
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-05
      • 2013-06-30
      • 2017-02-05
      • 2013-12-29
      相关资源
      最近更新 更多