Cam*_*auu 5 ruby-on-rails nested-attributes
我有嵌套属性的问题,我有下一个实体:
class Experience < ActiveRecord::Base
has_many :roles, inverse_of: :experience
end
class Role < ActiveRecord::Base
belongs_to :experience, inverse_of: :roles
end
Run Code Online (Sandbox Code Playgroud)
我有下一组参数:
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}]}
Run Code Online (Sandbox Code Playgroud)
我想更新一个 Rails 模型。所以我执行:
@experience = Experience.find(some_id)
@experience.update_attributes(params)
Run Code Online (Sandbox Code Playgroud)
这给我返回一个错误
ActiveRecord::RecordNotUnique:PG::UniqueViolation:错误:重复的键值违反了唯一约束“roles_pkey”
如果我看到 Rails 试图更新什么,我会看到下一条sql语句:
UPDATE“角色”SET“start_date”= $1,“end_date”= $2,“current”= $3,“id”= $4,“description”= $5,“title”= $6,“created_at”= $7,“updated_at” = $8 WHERE "角色"."id" = $9 [["start_date", nil], ["end_date", nil], ["current", nil], ["id", 561], ["description", nil],[“标题”,“测试”],[“created_at”,“2017-06-23 10:54:10.194605”],[“updated_at”,“2017-06-23 10:54:10.194605”] ,[“id”,558]]
这对我来说很奇怪,因为它试图更新记录id,如果您看到语句,您将看到:"id" = $4和 where 子句WHERE "roles"."id" = $9,这是正确的,但它采用两个不同的id值。
相反,如果我执行:
@experience = Experience.include(:roles).find(some_id)
@experience.update_attributes(params)
Run Code Online (Sandbox Code Playgroud)
效果很好
如果我进入 Rails 控制台并手动触发它,初始情况也会起作用。我不知道为什么会发生这种情况,当然应用程序更加复杂,我只是为您提供解决问题的基本数据,但任何见解都会有所帮助。
| 归档时间: |
|
| 查看次数: |
338 次 |
| 最近记录: |