【问题标题】:rails 4, postgres and arraysrails 4,postgres 和数组
【发布时间】:2015-07-07 17:46:03
【问题描述】:

我一直在关注一些关于使用 rails 4 和 postgres 存储数组的指南,但我一直被这个错误困扰:

PG::DatatypeMismatch: ERROR:  column "run_times" is of type character varying[] but expression is of type character varying at character 35
HINT:  You will need to rewrite or cast the expression.

这是 Rails 正在执行的 SQL:

UPDATE "models" SET "run_times" = $1, "updated_at" = $2 WHERE "models"."id" = $3  [["run_times", "{0,2}"], ["updated_at", "2015-07-07 17:44:47.480675"], ["id", 1]]

由控制器使用(作为示例)生成:

@model.run_times = ["0", "2"]

我有什么遗漏吗?

--

有趣的是,这似乎在 Rails 控制台中工作:

@model = Model.find(1)
@model.run_times = ["123", "456"]
@model.save

--

这是我使用的迁移:

class AddRunTimesToModel < ActiveRecord::Migration
  def change
    add_column :models, :run_times, :text, array: true, default: '{}'
  end
end

【问题讨论】:

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


    【解决方案1】:

    由于您正在传递字符串,因此请仔细检查您的 run_times 列是否在您的架构中为该模型的表设置了这样的设置?

    t.string :run_times, array: true, default: '{}'
    

    【讨论】:

    • 是的。在 psql 中确认输入:字符变化 []
    • 当您尝试执行 @model.run_times &lt;&lt; ["0", "2"] 然后保存时,rails 控制台会发生什么
    • 奇怪,当您设置 run_times 然后保存时控制器中发生的任何事情都会导致 ActiveRecord 将其解释为仅字符串或文本值,而不是实际的 Postgres 数组
    【解决方案2】:

    我相信通常的建议是在 PostgreSQL 中将基于字符串的数组定义为文本,而不是字符串。我会“关闭”迁移,并将类型更改为文本数组。

    【讨论】:

    • 切换它并得到相同的错误,不同的期望; column "run_times" is of type text[] but expression is of type character varying
    【解决方案3】:

    好吧,这就是我需要做的:

    • 而不是permit(:run_times) 它必须是permit(run_times: [])
    • rails 迁移中的类型是字符串,而不是文本
    • 迁移后重启服务器

    【讨论】:

    • 在 Rails 4 中,它通常会更新并且工作正常,在大多数情况下......但仍然是手掌。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-04
    • 1970-01-01
    • 2017-05-19
    相关资源
    最近更新 更多