【发布时间】:2013-01-09 19:33:03
【问题描述】:
我有一个模型:
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
这没有显示主键约束(或缺少主键约束),这是根本问题。
【问题讨论】:
-
你能在这里张贴
db/scheme.rb中显示other_things表方案的部分吗? -
已更新以显示请求的信息;还回答了最近发现的缺少主键约束的潜在问题。
标签: sql ruby-on-rails insert primary-key rails-activerecord