Background
I was reviewing Ryan Bates Railscast on deeply nested forms to use the new accepts_nested_attributes_for definition. Everything went swimmingly until I got to the objects with has_and_belongs_to_many definitions.My objects were somthing like this (this is just an example):
class Album < ActiveRecord::Base has_many :content, :dependent => :destroy accepts_nested_attributes_for :content, :allow_destroy => true end class Content < ActiveRecord::Base set_table_name "content" has_and_belongs_to_many :performers, :join_table => "content_performers" accepts_nested_attributes_for :performers, :allow_destroy => true has_and_belongs_to_many :producers, :join_table => "content_producers" accepts_nested_attributes_for :producers, :allow_destroy => true end class Performer < ActiveRecord::Base has_and_belongs_to_many :content end class Producer < ActiveRecord::Base has_and_belongs_to_many :content end
The Problem
Using the helper methods and javascript outlined in the railscast, I set up my forms and started testing. Looking at webrick, all the correct data was coming through the post. The album object saved just fine along with the embedded content. However, when I went to verify in the database, both the performers and producers were empty.The Answer
I did a lot of head scratching. Sifting through the code salad of the webrick output, I happened to notice this:WARNING: Can't mass-assign these protected attributes: performers_attributes WARNING: Can't mass-assign these protected attributes: producers_attributesModifying my Content class as follows:
class Content < ActiveRecord::Base set_table_name "content" has_and_belongs_to_many :performers, :join_table => "content_performers" accepts_nested_attributes_for :performers, :allow_destroy => true has_and_belongs_to_many :producers, :join_table => "content_producers" accepts_nested_attributes_for :producers, :allow_destroy => true attr_accessible :performers_attributes, :legal_producers_attributes endI was then able to continue using the forms without problems. I'm not sure if this is a bug or just a misunderstading on my part about how accepts_nested_attributes_for works, but either way, this bug is squashed for now. It would seem to me though these accessible attributes would be a given when declaring accepts_nested_attributes_for.