当我尝试通过 Rails 控制台更新 Puzzle
对象的 User
对象时,我得到一个数据库 ROLLBACK
并在开发中出现此错误:
类型错误:无法转换 ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Array::Data
只有当我尝试使用 update
(或 puzzle.user = some_user
之后的save
)时才会发生这种情况。添加初始所有者提交到数据库没有问题。
这里是架构中的模型:
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
设置为字符串数组,但您将整数压入其中。 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
关于ruby-on-rails - Rails 5.1.5:TypeError:无法转换 ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Array::Data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49437613/