数组字段未被识别为属性

jas*_*328 3 arrays postgresql attributes ruby-on-rails ruby-on-rails-4

我有我创建的以下模型,

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
Run Code Online (Sandbox Code Playgroud)

我还将pg数组解析器gem添加到我的Gemfile中.

问题在于,无论何时创建用户,它都会告诉我类别是未知属性.

User.create(name: "Bob", email: "bob@gmail.com", 
password: "password", password_confirmation: "password", categories: [1, 2])

The Error:

unknown attribute: categories
Run Code Online (Sandbox Code Playgroud)

怎么了?怎么解决这个问题?

更新:

跑完后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.
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 6

postgres_ext用于向Rails3添加数组支持的gem理解这default: '{}'意味着SQL应该说,'{}'::integer[]但我猜测Rails4驱动程序有点困惑,并说'{}'.to_i或类似的东西; 抱歉,我没有在任何地方设置Rails4,所以我不能更具体,但它确实符合您所看到的错误.

您可以尝试使用Ruby数组而不是PostgreSQL样式的数组字符串:

t.integer :categories, array: true, default: []
Run Code Online (Sandbox Code Playgroud)

这将触发正确的sql -ification,postgres_ext因此它也应该在Rails4中做正确的事情.