【发布时间】: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.rb 和user.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 => 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 = up.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