I setup a has_many through association with my models and I am trying to create a form where I can add multiple genres to a submitted song. I am using the collection_select helper for this. Here are snippets on how my code is setup.
Song Model
has_many :song_genres
has_many :genres, :through => :song_genres
Genre Model
has_many :song_genres
has_many :songs, :through => :song_genres
Song Genre Model
belongs_to :song
belongs_to :genre
Then in my new.html.erb
I have this
collection_select :song, :genres, Genre.all, :id, :name, {:selected => 1}, {:multiple => true}
When I submit the form I get a
Can't mass-assign protected attributes: genres
error
I know I’m missing something big here. Can someone help me out on how to properly set this up?
Thanks!
Try this way:
As stated in the Rails guide:
“If you are using select (or similar helpers such as collection_select, select_tag) to set a belongs_to association you must pass the name of the foreign key (in the example above city_id), not the name of association itself.”