2013-01-09 26 views
1

我有一個模型:Rails的update_attributes方法試圖插入ID列

class MyModel < ActiveRecord::Base 
    has_many :other_things 
    accepts_nested_attributes_for :other_things 
    attr_accessible :other_things_attributes 
end 

class OtherThing < ActiveRecord::Base 
    belongs_to :my_model 
    attr_accessible :foo 
end 

當試圖在爲MyModel實例update_attributes方法,軌道/ ActiveRecord的嘗試插入空到ID列:

my_instance = MyModel.first 
my_instance.update_attributes({ 
    "other_things_attributes"=> { 
    "1357758179583" => {"foo"=>"bar", "_destroy"=>"false"}, 
    "1357758184445" => {"foo"=>"thing", "_destroy"=>"false"} 
    } 
}) 

失敗,有:

SQL (0.5ms) INSERT INTO "other_things" ("created_at", "my_model_id", "id", "updated_at", "foo") VALUES ($1, $2, $3, $4, $5) [["created_at", Wed, 09 Jan 2013 14:30:33 EST -05:00], ["my_model_id", 8761], ["id", nil], ["updated_at", Wed, 09 Jan 2013 14:30:33 EST -05:00], ["foo", "bar"]] 
    (0.1ms) ROLLBACK 
ActiveRecord::StatementInvalid: PGError: ERROR: null value in column "id" violates not-null constraint 
: INSERT INTO "other_things" ("created_at", "my_model_id", "id", "updated_at", "foo") VALUES ($1, $2, $3, $4, $5) 

架構顯示other_things:

create_table "other_things", :force => true do |t| 
    t.string "foo" 
    t.integer "my_model_id" 
    t.datetime "created_at", :null => false 
    t.datetime "updated_at", :null => false 
    end 

這沒有顯示的是主要的約束(或缺少),這是潛在的問題。

+0

你可以在這裏發佈'db/scheme.rb'顯示'other_things'表格方案的部分嗎? – daniloisr

+0

已更新,以顯示請求的信息;還回答了最近發現的缺少主鍵約束的潛在問題的問題。 – pcragone

回答

1

這是由於某種原因丟失了other_things表上的主鍵規範。我確定了這一點,因爲我必須將實例(分段和生產)分開,而在其中一個而不是另一箇中運行。在比較代碼和Rails相關的問題之後,我決定對DB模式進行區分,這些模式向我展示了缺少的主鍵約束。顯然,Rails使用主鍵來標識正確的列;直覺上顯而易見,但如果您不知道我的意見,則不會。感謝您的評論!

ALTER TABLE ONLY other_things ADD CONSTRAINT other_things_pkey PRIMARY KEY (id); 
0

有類似的問題,我通過使用update_columns而不是update_attributes解決。希望它能幫助別人。 :)

相關問題