【问题标题】:Rails enum negative scope (where not)Rails 枚举负范围(不是)
【发布时间】:2016-03-17 21:18:11
【问题描述】:

我使用enum 作为users 表中的一列。我希望能够找到所有未挂起的用户。这是我当前的代码:

enum approval_status: [:pending, :approved, :declined]

User.where.not(approval_status: :pending)

但是SQL查询变成了这样:

User Load (0.5ms)  SELECT `users`.* FROM `users` WHERE (`users`.`approval_status` != NULL)

无论我输入什么枚举值,SQL 都会将其转换为 NULL

我如何获得所有用户,除了approval_status 列的特定值?

【问题讨论】:

    标签: ruby-on-rails scope


    【解决方案1】:

    在 Rails 6 中,在枚举值上添加了负作用域。

    你可以这样使用它:

    User.not_pending
    User.not_approved
    User.not_declined
    

    相关pull request

    【讨论】:

      【解决方案2】:

      在这种情况下,Rails 无法处理符号。 但是,字符串可以正常工作 字符串也会损坏,但方式不同:

      enum approval_status: [:pending, :approved, :declined]
      
      User.where.not(approval_status: :pending) //breaks
      User.where.not(approval_status: 'pending') //returns 0 no matter what the string is.
      

      更新

      上面的答案实际上不起作用。任何字符串都返回0(所以如果你正在寻找你的第一个枚举,它似乎可以工作)。

      以下内容将实际使用您的枚举:

      User.where.not("user.approval_status = ?", User.approval_statuses[:pending])
      

      注意——Rails 5 将有更好的枚举范围支持。

      【讨论】:

      • @dezman 在 Rails 5 中你可以做 where.not(approval_status: :pending) 并且它工作正常
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多