【问题标题】:My Enums is not working on where clauses我的枚举不适用于 where 子句
【发布时间】:2015-07-29 18:04:12
【问题描述】:

我有以下型号

class Request < ActiveRecord::Base
    # Enumerables
    enum status: [:pending, :accepted, :completed]
end

迁移看起来像这样:

class CreateRequests < ActiveRecord::Migration
    def change
        create_table :requests do |t|
            t.column    :status, :integer, default: 0, index: true
        end
    end
end

为了问题而简化。

现在,关于我的 Enums 的一切工作正常。

@request.pending?
@request.accepted!
# And so on...

但是当我执行以下查询时:

Request.where(status: :accepted)

这是我的日志显示的内容:

SELECT "requests".* FROM "requests" WHERE "requests"."status" = NULL LIMIT 20 OFFSET 0

这显然是错误的,因为NULL。现在我知道我可以做到这一点

Request.accepted

但另一种方式也应该有效,如the documentation 中所述。

发生了什么事??

【问题讨论】:

  • 那些不是可枚举的,它们是枚举。大不同!

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


【解决方案1】:

试试这个

accepted_requests = Request.accepted

参考:In Rails 4.1, how to find records by enum symbol?

【讨论】:

  • 在这种情况下,日志显示:SELECT "requests".* FROM "requests" WHERE "requests"."status" = ? LIMIT 20 OFFSET 0 [["status", 1]] 我猜它是正确的,但其他方式应该也可以,不是吗?
  • 没有这个链接edgeapi.rubyonrails.org/classes/ActiveRecord/Enum.html解释了原因。我引用:Note that when an Array is used, the implicit mapping from the values to database integers is derived from the order the values appear in the array. In the example, :active is mapped to 0 as it's the first element, and :archived is mapped to 1. In general, the i-th element is mapped to i-1 in the database... 这个工作吗Request.where(status: [:accepted])
  • 主要原因是因为它们被映射到数据库中的整数而不是按值。因此,当您将字符串传递给整数查询时,它将不起作用。阅读第一行Declare an enum attribute where the values map to integers in the database,
  • 但我在文档中声明了枚举。并且文档试图做一个地方,就像我做的那样。那么区别在哪里呢?
  • 是的,但文档并没有说您可以使用字符串作为条件查询模型。实际上,枚举首先必须将您在数组中传递的状态映射到与数组顺序相同的整数中,并基于该整数使用该整数查询表,因为数据库中的状态类型也是整数而不是字符串。我猜您缺少表中的整数部分和查询中的字符串。而且。这就是为什么 Enum 为您提供将状态称为范围本身以使事情变得简单的原因
【解决方案2】:

我刚刚意识到我尝试使用的功能不可用,因为我一直在阅读Edge 版本的文档,该文档可能还没有发布。愚蠢的错误。

【讨论】:

    猜你喜欢
    • 2013-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多