我遇到了nested_attributes的问题,我有下一个实体:
class Experience < ActiveRecord::Base
has_many :roles, inverse_of: :experience
end
class Role < ActiveRecord::Base
belongs_to :experience, inverse_of: :roles
end
我有下一组参数:
params = {"end_date"=>"02/01/2012",
"city"=>"Buenos Aires",
"state"=>"",
"country"=>"",
"title"=>nil,
"company"=>"Restorando",
"current"=>nil,
"description"=>nil,
"roles_attributes"=>
[{"id"=>558, "title"=>"System Owner", "start_date"=>"03/01/2000", "end_date"=>"02/01/2001", "description"=>"<p>I did a bunch of stuff</p>", "current"=>false},
{"id"=>561, "title"=>"Test", "description"=>nil, "current"=>nil},
{"id"=>557, "title"=>"Full Stack Developerr", "start_date"=>"01/01/2011", "end_date"=>"02/01/2012", "description"=>"<p>Full Stack Developer description</p>", "current"=>false}],
"resumes_experiences_attributes"=>[{"id"=>384, "resume_id"=>809}, {"id"=>385, "resume_id"=>3199}]}
我想更新一个rails模型。所以我执行:
@experience = Experience.find(some_id)
@experience.update_attributes(params)
这会给我一个错误
ActiveRecord :: RecordNotUnique:PG :: UniqueViolation:ERROR:重复 键值违反了唯一约束&#34; roles_pkey&#34;
如果我看到Rails尝试更新的内容,我会看到下一个sql
声明:
更新&#34;角色&#34; SET&#34; start_date&#34; = $ 1,&#34; end_date&#34; = $ 2,&#34;当前&#34; = 3美元, &#34; ID&#34; = $ 4,&#34;描述&#34; = 5美元,&#34;标题&#34; = $ 6,&#34; created_at&#34; = 7美元, &#34;的updated_at&#34; = $ 8 WHERE&#34;角色&#34;。&#34; id&#34; = $ 9 [[&#34; start_date&#34;,nil], [&#34; end_date&#34;,nil],[&#34;当前&#34;,nil],[&#34; id&#34;,561],[&#34;说明&#34;, nil],[&#34; title&#34;,&#34; Test&#34;],[&#34; created_at&#34;,&#34; 2017-06-23 10:54:10.194605&#34 ], [&#34; updated_at&#34;,&#34; 2017-06-23 10:54:10.194605&#34;],[&#34; id&#34;,558]]
对我来说很奇怪,因为它正在尝试更新记录id
,如果你看到你将看到的陈述:"id" = $4
和where WHERE "roles"."id" = $9
这是id
正确,但它采用两个不同的@experience = Experience.include(:roles).find(some_id)
@experience.update_attributes(params)
值。
相反,如果我执行:
true
完美无缺
如果我进入rails控制台并手动触发它,初始情况也会起作用。我不知道为什么会发生这种情况,当然应用程序中存在更多的复杂性,我只是给你解决它的基本数据,但任何见解都会有所帮助。