【问题标题】:Rails 5.1.5: TypeError: can't cast ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Array::DataRails 5.1.5:TypeError:无法转换 ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Array::Data
【发布时间】:2018-09-01 10:03:54
【问题描述】:

当我尝试通过 Rails 控制台更新 Puzzle 对象的 User 对象时,我得到一个数据库 ROLLBACK 并出现此错误:

TypeError: can't cast ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Array::Data

这只发生在我尝试使用update(或save 之后的puzzle.user = some_user)时。添加初始所有者提交到数据库没有问题。

以下是架构中的模型:

create_table "users", force: :cascade do |t|
  t.string "username"
  t.string "password_digest"
  t.string "email"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.integer "location_id"
end

create_table "puzzles", force: :cascade do |t|
  t.string "name"
  t.integer "pieces"
  t.integer "missing_pieces"
  t.string "previous_owners", array: true
  t.integer "user_id"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

这是目前为止的puzzle.rbuser.rb 文件:

class User < ApplicationRecord
    validates :username, presence: true
    validates :email, presence: true#, uniqueness: true
    # use bcrypt for password security
    has_secure_password

    has_many :puzzles
    has_many :reviews
    belongs_to :location
end

class Puzzle < ApplicationRecord
    validates :name, uniqueness: true
    validates :pieces, presence: true, numericality: { only_integer: true }

    belongs_to :user
    has_many :puzzle_tags
    has_many :tags, through: :puzzle_tags
    has_many :reviews
    delegate :location, to: :user
end

知道是什么导致了这个问题吗?

***请注意:我是新手,第一次使用 PostgreSQL。我特别选择 Postgres 作为我的开发数据库而不是 SQLite3,因为它允许数组数据类型。谢谢!

【问题讨论】:

  • 您是否有任何代码尝试更新previous_owners
  • 您尝试在控制台中更新用户的具体情况如何?
  • 尝试保存记录而不进行验证,例如puzzle.save(:validate =&gt; false)。如果它有效,那么它是一个验证问题。我的猜测是您为数据库中的字段分配了错误的类型,例如将字符串分配给整数
  • @moveson 我在控制台中将拼图的 previous_owners 设置为一个空数组(即puzzle.previous_owners = [])(最终我将添加该数组作为默认值)
  • @muistooshort p = Puzzle.new(name: "Some puzzle", pieces: 1000) u = User.new(username: "user", email: "blah@blah.com", password: "34532h4gktj2hg") p.user = u p.save (没问题)u2 = User.new(username: "user", email: "blah2@blah.com", password: "34532h4gktj2hg") p.update(user_id: u2.id) (导致回滚和错误)也试过:p.user = u2 然后p.save 和得到同样错误的回滚。

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


【解决方案1】:

您已将previous_owners 设置为字符串数组,但您将整数推入其中。 ActiveRecord 擅长将字符串转换为整数,反之亦然,但从 Rails 5.1.5 开始,该功能在数组字段中不起作用。

尝试使用迁移将字段更改为整数数组。你需要这样做:

$ rails g migration change_previous_owners_to_integer_array

然后像这样编辑生成的迁移文件:

def change
  remove_column :puzzles, :previous_owners, :string, array: true
  add_column :puzzles, :previous_owners, :integer, array: true
end

【讨论】:

    猜你喜欢
    • 2016-09-22
    • 1970-01-01
    • 2011-04-07
    • 2017-05-14
    • 2021-05-19
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多