我有一个模型:
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 实例上更新属性时,Rails/ActiveRecord 尝试将 null 插入 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
这没有显示主键约束(或缺少主键约束),这是根本问题。