数组字段未被识别为属性

时间:2013-07-18 18:17:21

标签: ruby-on-rails arrays postgresql attributes 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

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

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

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.

1 个答案:

答案 0 :(得分:6)

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

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

t.integer :categories, array: true, default: []

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