views:

61

answers:

1

Guys,

I was wondering if it was possible to create new parent, children in a has many relationship, using rails nested forms.

Rails documentation clearly says that this works in a one to one relationship. Not sure if its the same in has many relationship.

For example:

If

params = { 
  :employee => { 
    :name => "Tester", 
    :account_attributes => {:login => 'tester'}
  }
} 

works as one to one relationship. So Employee.new(params) works fine. New employee, account are created.

Supposing I had

params = { 
  :employee => { 
    :name => "Tester", 
    :account_attributes => {
      "0" => {:login => 'tester'}, 
      "1" => {:login => 'tester2'}
    }
  }
} 

Employee.new(params) doesnt work. It fails on child validations saying parent cant be blank.

Any help is appreciated. Thanks

Karen

+2  A: 

The child_attributes= writer that comes with accepts_nested_attributes_for expects an array when it comes to one to many relationships.

This will create two accounts for the new employee

params = { 
  :employee => { 
    :name => "Tester", 
    :account_attributes => [
     {:login => 'tester'}, 
     {:login => 'tester2'}
    ]
  }
} 
EmFi