问题
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