【发布时间】:2013-07-18 18:17:20
【问题描述】:
我创建了以下模型,
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :email
t.string :password_digest
t.string :location_type
t.integer :location_id
t.integer :categories, array: true, default: '{}'
t.timestamps
end
add_index :user, :email, unique: true
end
end
我还在我的 Gemfile 中添加了 pg 数组解析器 gem。
问题是每当我创建用户时,它都会告诉我类别是未知属性。
User.create(name: "Bob", email: "bob@gmail.com",
password: "password", password_confirmation: "password", categories: [1, 2])
The Error:
unknown attribute: categories
出了什么问题,我该如何解决?
更新:
在运行rake db:drop db:create db:migrate 之后,我遇到了这个新错误。
PG::Error: ERROR: column "categories" is of type integer[] but default expression is of type integer
HINT: You will need to rewrite or cast the expression.
【问题讨论】:
-
你检查过你在 PostgreSQL 中的
users表吗?来自psql的简单\d users将告诉您该表的真实外观。 -
我在
schema.rb中没有看到类别字段,所以我重置了数据库。结果显示在答案中。 -
您是否尝试过
default: []或default: "'{}'::integer[]"? The old postgres_ext gem for Rails3 properly casts'{}'` 到'{}'::integer[]但也许 Rails4 变得混乱并改为使用'{}'.to_i。 -
谢谢@mu。使用
default: []有效。发布它作为答案,我会给你信用。
标签: ruby-on-rails arrays postgresql attributes ruby-on-rails-4