【问题标题】:Rails 5 Polymorphic association with enum is throwing `ERROR: invalid input syntax for type integer`Rails 5 与枚举的多态关联抛出“错误:整数类型的输入语法无效”
【发布时间】:2021-06-23 06:00:35
【问题描述】:

我有一个Log模型,通过多态关联属于很多模型。对于类型列,它使用enum,它在 Rails 4.2 上运行良好,但升级到 Rails 5 后,它正在抛出 ERROR: invalid input syntax for type integer

class Log
  enum loggable_type: %i[a b c d]
  # ...
end
class A
  has_many :logs, as: :loggable, dependent: :destroy
  # ...
end

获取日志时:

a = A.find id
a.logs

它会抛出以下错误:

ActiveRecord::StatementInvalid (PG::InvalidTextRepresentation: ERROR:  invalid input syntax for type integer: "A")
: SELECT "logs".* FROM "logs" WHERE "logs"."loggable_id" = $1 AND "logs"."loggable_type" = $2

在 Rails 4.2 中,相同的代码运行良好。这是相同的查询:

> a.logs
  Log Load (2.0ms)  SELECT "logs".* FROM "logs" WHERE "logs"."loggable_id" = $1 AND "logs"."loggable_type" = $2  [["loggable_id", 1111111], ["loggable_type", 0]]
 => #<ActiveRecord::Associations::CollectionProxy []>

我需要做什么才能使其适用于 Rails 5?

【问题讨论】:

  • 你可以尝试明确定义枚举,enum loggable_type: {a: 'A', b: 'B', c: 'C'},因为现在如果你做 Logs.loggable_types 你会得到{a: 0, b: 1, c: 2}
  • loggable_type列类型迁移到字符串
  • 谢谢大家帮忙。我找到了解决方案并发布了相同的内容。
  • @Int'lManOfCodingMystery 让我试试你的解决方案,看看它是否有效,但我已经使用 polymorphic_integer_type gem 解决了这个问题。

标签: ruby-on-rails ruby ruby-on-rails-5


【解决方案1】:

根据 Rails 文档和here 提出的问题,多态类型列应该是字符串,而不是整数。使用这种方法,我不得不迁移旧数据。

幸运的是,有一个 gem polymorphic_integer_type 可以解决完全相同的问题。

在 Gemfile 中包含 gem 并运行 bundle 后,我所要做的就是:

class Log
  include PolymorphicIntegerType::Extensions
  belongs_to :loggable, polymorphic: { 1 => 'A', 2 => 'B', 3 => 'C', 4 => 'D' }
end

它就像一个魅力。

【讨论】:

    猜你喜欢
    • 2023-01-26
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    • 2016-05-18
    • 1970-01-01
    • 2014-03-30
    • 1970-01-01
    • 2012-12-21
    相关资源
    最近更新 更多