Rails accepted_nested_attributes_for错误,请帮我发现它

时间:2010-11-07 17:52:48

标签: ruby-on-rails activerecord

我一直试图关注Active Record Nested Attributes Guide,但没有取得多大成功。

我有以下型号:

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

class Telephone < ActiveRecord::Base
  belongs_to :contact
end

尝试创建联系人时:

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

我收到以下错误: ActiveRecord::AssociationTypeMismatch: Telephone(#80827590) expected, got Hash(#72886250)

你可以帮我发现错误吗? 我应该在contact_controller.rb中包含哪些代码?

1 个答案:

答案 0 :(得分:10)

我使用以下代码:

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

我将错误的参数传递给Contact.create控制器......