使用rails中的复合键更新模型嵌套属性
我有一个具有one_to_many关系的模型:
class Work < ActiveRecord::Base has_many :work_right_holders accepts_nested_attributes_for :work_right_holders, allow_destroy: true end class WorkRightHolder < ActiveRecord::Base self.primary_keys = :work_id, :right_holder_id, :role belongs_to :work belongs_to :right_holder end
当我尝试使用嵌套属性更新work
时,它会在关系中创建对象的新实例,而不是基于其主键更新现有实例:
work.update( {"work_right_holders_attributes"=> { "0"=>{ "role"=>"Author", "right_holder_id"=>"2", "work_id"=>work.id, "share"=>"11" } } } )
为什么会这样?
您需要传递集合对象ID,如下所示:
work.update( {"work_right_holders_attributes"=> { "0"=>{ "role"=>"Author", "right_holder_id"=>"2", "work_id"=>work.id, "share"=>"11", "id" => [work.id, "2", "Author"] } } } )
这应该工作。
obs:在Rails 4.1.1中有一个错误,这不起作用,但在Rails 4.2.1中它正在工作