2013-07-18 40 views
3

我有以下的模型,我創建,陣列場無法被識別爲屬性

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陣列解析器寶石我的Gemfile。

問題是,無論何時我創建用戶,它都會告訴我類別是未知屬性。

User.create(name: "Bob", email: "[email protected]", 
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. 
+0

你在PostgreSQL中檢查過你的用戶表嗎? 'psql'中的一個簡單的'\ d用戶'會告訴你表的真實外觀。 –

+0

我沒有看到'schema.rb'中的類別字段,所以我重置了數據庫。結果顯示在答案中。 – jason328

+2

您是否嘗試過'default:[]'或'default:''{}':: integer []「? Rails3的舊的postgres_ext gem正確地將''{}''轉換爲''{}':: integer []',但是也許Rails4會變得混亂,而不是做'{}'。to_i'。 –

回答

6

postgres_ext寶石添加陣列支持Rails3中瞭解到,default: '{}'意味着,SQL應該說'{}'::integer[]但我猜測,該Rails4司機開始有點糊塗,說'{}'.to_i或類似的東西;對不起,我沒有在任何地方設置Rails4,所以我不能更具體,但它確實符合你所看到的錯誤。

你可以嘗試使用Ruby的陣列,而不是PostgreSQL式陣列字符串:

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

將觸發正確的-SQL-ification與postgres_ext所以它應該做的正確的事Rails4太。