Felix
Felix

Reputation: 89576

Mass assignment 2 levels deep?

My models looks something like this (stripped down to the bare minimum for this question):

class Translation < ActiveRecord::Base
  has_many :array_resources
end
class ArrayResource < ActiveRecord::Base
  attr_accessible :array_items
  has_many :array_items
  accepts_nested_attributes_for :array_items
end

Now, in my Translation model I have a method in which I call array_resources.build(params), where params is an array of hashes, where each hash also contains an :array_items key, mapped to another array of hashes.

Unfortunately, I get the following error:

ActiveRecord::AssociationTypeMismatch in ProjectsController#create

ArrayItem(#69835262797660) expected, got Hash(#18675480)

Every other answer I read talked about using accepts_nested_attributes_for, but I already did that. Help?

Upvotes: 2

Views: 128

Answers (1)

Wizard of Ogz
Wizard of Ogz

Reputation: 12643

You shouldn't assign to nested attributes array_items directly, but rather array_items_attributes.

You should make :array_items_attributes accessible:

class ArrayResource < ActiveRecord::Base
  attr_accessible :array_items_attributes

Then in your params hash use the key :array_items_attributes instead of :array_items.

Upvotes: 2

Related Questions