I have altogether three models: User, Album and Genre. User refers to artist(singer, compose, musician etc). An album can have many artists(users) and many genres. An artist can compose/sing for many albums.In short I have following models and controller action . I have created two HABTM relations: albums_genres and users_albums in db.
//User model
class User < ActiveRecord::Base
has_and_belongs_to_many :albums
end
//Album model
class Album < ActiveRecord::Base
has_and_belongs_to_many :genres
has_and_belongs_to_many :users
end
//Genre model
class Genre < ActiveRecord::Base
has_and_belongs_to_many :albums
end
//albumController create method
def create
@user = current_user
@album = @user.albums.new(params[:album])
if @album.save
...
end
end
When I send data as follows, data is inserted properly in albums_users.
"Album"=>{"title"=>"Test album", "description"=>"test description"
However I want insert data into albums_genres table as well. For this, my params data looks like:
"Album"=>{"title"=>"Test album", "description"=>"test description", "genre_ids"=>["1", "2", "3"]}
Then I got an error Can't mass-assign protected attributes: genre_ids. It's trying to insert data into albums table which I believe should insert genre_ids into albums_genres. So my question is how do i need to write controller code? Better way to write controller and/or model code is highly appreciated. Thank you in advance! Reference taken from: http://railscasts.com/episodes/17-habtm-checkboxes