rails/rails — pull request #15128 by D1plo1d (2014-05-15 21:23:08+00:00)
Title: Adding nested attributes options: keys and overwrite

This PR is a proof of concept (posted for feedback) adding 2 options to AR nested has_many associations:

1. **keys** - an array of column names can be specified causing AR to look nested models by any of the column names specified. For example:
```
accepts_nested_attributes_for :shared_order_items, :seats, :waiter, :table, keys: %i(id uuid)
```
is going to look up seats, waiters and tables by either an id or a uuid depending on which is supplied in the attributes hash. For my purposes (where I am building an API which needs to update nested models via their uuids) this is really useful since my other option was to override the writers (ex. seats_attributes=) with my own implementation every time I wanted to use a non-id lookup which started to get very kludgy very quickly.

2. **overwrite** - if true the entire set of nested child models will be overwritten by the new + updated models specified in the attributes hash. What that means behind the scenes is that we delete any omitted models. This is primarily for building APIs that have to interface with 3rd parties which want to delete child models that aren't present on their side but aren't aware of which particular child models have been removed. For example:
```
accepts_nested_attributes_for :shared_order_items, :seats, :waiter, :table, overwrite: true
```

These 2 changes have really simplified a codebase that I'd been struggling to keep clean before the patch. I'd love feedback on this.

To try it out in your own rails 4 project you can copy `activerecord/lib/active_record/nested_attributes.rb` into your `config/initializers` folder (it causes a couple warnings about duplicate definitions but it works).