我有一個模型: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
這沒有顯示的是主要的約束(或缺少),這是潛在的問題。
你可以在這裏發佈'db/scheme.rb'顯示'other_things'表格方案的部分嗎? – daniloisr
已更新,以顯示請求的信息;還回答了最近發現的缺少主鍵約束的潛在問題的問題。 – pcragone