Habtm association and accepts_nested_attributes_for


#1

hi all,

i have the following models:

class Developer < ActiveRecord::Base
has_and_belongs_to_many :projects
accepts_nested_attributes_for :projects
end

class Project < ActiveRecord::Base
has_and_belongs_to_many :developers
accepts_nested_attributes_for :developers
end

the following code:

params = { ‘form’ => { ‘name’ => ‘gonzalo’, ‘dni’ => ‘12876365x’,
‘projects_attributes’ => {
‘new_01’ => { ‘name’ => ‘Sioux’, ‘cost’ => ‘25000’ },
‘new_02’ => { ‘name’ => ‘Apache’, ‘cost’ =>
‘3400’}}}}
Developer.create(params[‘form’])

will create a new Developer and two new Projects and the corresponding
association between Developer and Projects.

then, I add a new Developer using the same mechanism:

params = { ‘form’ => { ‘name’ => ‘paul’, ‘dni’ => ‘17002034z’,
‘projects_attributes’ => {
‘1’ => { ‘name’ => ‘ZZZZ’, ‘cost’ => ‘25000’ },
‘2’ => { ‘name’ => ‘YYYY’, ‘cost’ => ‘3400’}}}}
Developer.create(params[‘form’])

following NestedAttributes documentation… this code should add a new
Developer (paul) and link it against the two already created Projects
with ids 1 and 2. Besides, this code should modiify projects names
from Sioux and Apache to ZZZZ and YYYY respectively.

the real result is that a new Developer (paul) is added but linked
against two new Projects (ZZZZ and YYYY)

am I doing something wrong? should i use another approach to face this
problem? is accept_nested_attributes_for feature compatible with habtm
associations?

and last… what if i just want to create a new Developer (paul) that
is associated with the already created Projects with ids 1 and 2? The
following code won’t work:

params = { ‘form’ => { ‘name’ => ‘paul’, ‘dni’ => ‘17002034z’,
‘projects_attributes’ => {
‘1’ => { },
‘2’ => { }}}}
Developer.create(params[‘form’])

thanks in advance for your help!
regards.


#2

Try using the ID inside (this works for me):

params = { ‘form’ => { ‘name’ => ‘paul’, ‘dni’ => ‘17002034z’,
‘projects_attributes’ => {
‘1’ => { ‘id’ => ‘1’, ‘name’ => ‘ZZZZ’, ‘cost’ =>
‘25000’ },
‘2’ => { ‘id’ => ‘2’, ‘name’ => ‘YYYY’, ‘cost’ =>
‘3400’}}}}

An element with an ID is considered to be updated instead of created.