当我试图通过Rails控制台更新Puzzle对象的User对象时,我得到了一个包含此错误的数据库User:
TypeError: can't cast 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,因为它允许数组数据类型。谢谢!
发布于 2018-03-23 04:34:00
您将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
endhttps://stackoverflow.com/questions/49437613
复制相似问题