# Examples of Nesting Associated Attributes # This is a look at the various ways to set associated attributes through # nested parameters. For example, let's say Project has_many :tasks and # we want to update the tasks the same time we edit a project. There are # several ways this interface could be handled, and here are a few. # # For these examples, we're trying to create two new tasks and update an # existing task (with id 3) through a project. # Approach 1 # This is the first interface I demonstrated in the 3 Railscasts # episodes. Here the tasks are all passed in an array with a hash of # attributes for each. Only the existing tasks have an :id attribute. # http://railscasts.com/episodes/75 # This is also the same interface David Dollar uses in his approach. # http://groups.google.com/group/rubyonrails-core/browse_thread/thread/4049b4b313fa8be2 { :tasks => [ { :id => 3, :name => 'Foo' }, { :name => 'Bar' }, { :name => 'Baz' } ] } # Approach 2 # This one is from the Advanced Rails Recipes book. The tasks are split # up into two different keys: 'existing_task_attributes' which task a # hash and 'new_task_attributes' which task an array. # http://media.pragprog.com/titles/fr_arr/multiple_models_one_form.pdf { :existing_task_attributes => { '3' => { :name => 'Foo' } }, :new_task_attributes => [ { :name => 'Bar' }, { :name => 'Baz' } ] } # Approach 3 # From Eloy Duran's nested_params plugin. This takes a single # :tasks parameter which is a hash, new records start with "new_" and # have a unique identifier (sometimes the object_id). # http://github.com/alloy/complex-form-examples/tree/alloy-nested_params { :tasks => { '3' => { :name => 'Foo' }, 'new_24235' => { :name => 'Bar' }, 'new_35234' => { :name => 'Baz' } } } # Approach 4 # From Dave Rothlisberger's post on the mailing list. This takes a :tasks # hash, each with a unique key usually generated by an incrementing # number. Like Approach 1, only the existing tasks have an :id attribute. # http://groups.google.com/group/rubyonrails-core/browse_thread/thread/3c61e00916c365e5/69ec67ab6380bc53?show_docid=69ec67ab6380bc53 { :tasks => { '1' => { :id => '3', :name => 'Foo' }, '2' => { :name => 'Bar' }, '3' => { :name => 'Baz' } } } # Approach 5 # From Josh Susser's patch. This is similar to Approach 2, except a hash # is used instead of an array for new tasks. The hash key can be anything # unique and sortable, such as an incrementing number, the object_id, or # the current time. # http://rails.lighthouseapp.com/projects/8994/tickets/1031 { :update_tasks_params => { '3' => { :name => 'Foo' } } :create_tasks_params => { '1' => { :name => 'Bar' }, '2' => { :name => 'Baz' } } }