rails/rails — Issue #3411: nested_attributes problem when primary key is not id
Author: eLod
Created: 2011-10-23 20:05:27+00:00
State: open

There was a [lighthouse ticket](https://rails.lighthouseapp.com/projects/8994/tickets/4395-bug-in-nested_attributes-when-the-primary-key-is-not-id) and [several](https://github.com/rails/rails/commit/f194d65f36be29971601664c880cb9b23ee2a95b) [fixes](https://github.com/rails/rails/commit/38da0ace772e6f9f5e2fff74db76237ab31790fa) for it, but `assign_nested_attributes_for_one_to_one_association` and `assign_nested_attributes_for_collection_association` both still check `record.id.to_s == attributes['id'].to_s` which obviously fails (and in my case for a has_many association it raises an `ActiveRecord::RecordNotFound` exception although i see it found the record with the correct query which is because of the mentioned patches), and should be something like `record.send(record.class.primary_key).to_s == attributes['id'].to_s` in both cases (although `assign_nested_attributes_for_collection_association` already uses `association.klass.primary_key`, so it could be reused).

I think however using the correct field name would be better and it would also support composite primary keys too. As `assign_nested_attributes_for_collection_association` already checks for the primary key (to construct the conditions) it could simply check for that key in the hash and not 'id' (and it could support not only single keys). For this to work `fields_for` (in `ActionView::Helpers::FormHelper`) should be changed to emit the correct hidden field(s).