0

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

1 Answers1

0

You have to add genre_ids to you mass assignable attributes:

attr_accessible :genre_ids

then your data creates the record in albums_genres.

In your Album you get the collections genres and genre_ids. The first holds an array of Genre objects, the second an array of just the ids of the genres.
You can add or assign to both of these arrays, to manage the assocciation.
Mass assignment just sets the genre_ids but needs explicit permission for that (mass assignment restrictions).

Martin M
  • 8,430
  • 2
  • 35
  • 53
  • On top of this, put your `current_user.id` as a `hidden_field` in your form, it's messy code to be saving a `User` in your `AlbumsController#create` action (`hidden_field_tag "user_ids[]", current_user.id`) – Mike Campbell Jul 21 '13 at 12:39