【问题标题】:`.where` ARel query with enum mapped column returns exclusively entries with `0`带有枚举映射列的“.where”ARel 查询仅返回带有“0”的条目
【发布时间】:2016-02-19 08:02:05
【问题描述】:

我有一个模型,其中一个字段有一个枚举。

class Foo < ActiveRecord::Base

   enum status: [:yes, :no, :maybe, :so]

end

Status 是一个整数类型的字段。对于任何Foo 记录,我可以使用foo.yes!, foo.no! 等,并且对应的记录按预期返回foo.yes?, foo.no? 的true。

但是,当我尝试查询所有status='no'、status='maybe' 或status='so' 记录(使用方法Foo.where(status: 'no')、Foo.where(status: 'maybe') 等)时,它总是返回status='yes' 的条目。我检查了原始 SQL 查询,它似乎总是只查询 status=0 或状态为 yes 的时间。

为什么会这样?

【问题讨论】:

    标签: ruby-on-rails activerecord arel


    【解决方案1】:

    ActiveRecord 没有提供这样一个查询枚举的接口。 可以查询

    Foo.where(status: 0)
    

    或者

    Foo.yes
    

    【讨论】:

      【解决方案2】:

      因为 Arel 尝试将提供的字符串转换为整数并在查询中使用该整数。这是预期的行为。

      为了解决您的问题,您可以使用Array#index 方法:

      Foo.where(status: Foo.statuses.index('no'))
      

      但这种方法只有在您直接使用 Arel 时才需要。 ActiveRecord 已经为您关心它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-21
        • 1970-01-01
        • 2013-12-18
        • 2013-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多