Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails accepts_nested_attributes_for Error, please help me spot it

I have been trying to follow the Active Record Nested Attributes Guide, without much success.

I have the following models:

class Contact < ActiveRecord::Base
  has_many :telephones
  accepts_nested_attributes_for :telephones
end

class Telephone < ActiveRecord::Base
  belongs_to :contact
end

When trying to create a contact:

contact = {
  :name => "John",
  :telephones => [
    {:telephone => '787445741'},
    {:telephone => '478589658'}
  ]
}
Contact.create(contact)

I get the following error: ActiveRecord::AssociationTypeMismatch: Telephone(#80827590) expected, got Hash(#72886250)

Could you please help me spot the error? Is there any code that I should include in the contact_controller.rb?

like image 318
jfanals Avatar asked Nov 07 '10 17:11

jfanals


1 Answers

I got it working with the following code:

params = { :contact => {
    :name => 'Joe',
    :permanentcomment => "No Comment",
    :telephones_attributes => [
      {:telephone => '787445741'},
      {:telephone => '478589658'}
    ]
  }}
  Contact.create(params[:contact])

I was passing the wrong arguments to the Contact.create controller...

like image 151
jfanals Avatar answered Nov 08 '22 08:11

jfanals