Update model nested attributes with composite key in rails

情到浓时终转凉″ 提交于 2020-01-06 17:09:33

问题


I have a model with one_to_many relatioship:

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

When I try to update a work with nested attributes, it create new instances of object in the relationship, instead of updating the existing based on their primary key:

work.update(
  {"work_right_holders_attributes"=>
    {
     "0"=>{ "role"=>"Author", 
            "right_holder_id"=>"2", 
            "work_id"=>work.id, 
            "share"=>"11"
           }
     }
  }
)

Why is this happening?


回答1:


You need to pass the collection object id, like this:

work.update(
  {"work_right_holders_attributes"=>
    {
     "0"=>{ "role"=>"Author", 
            "right_holder_id"=>"2", 
            "work_id"=>work.id, 
            "share"=>"11",
            "id" => [work.id, "2", "Author"]
           }
     }
  }
)

This should work.

obs: in Rails 4.1.1 there is a bug an this does not work, but in Rails 4.2.1 it is working



来源:https://stackoverflow.com/questions/30674468/update-model-nested-attributes-with-composite-key-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!