Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to save data if you have two HABTM relations in a single model?
    text
    copied!<p>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 . <strong>I have created two HABTM relations: albums_genres and users_albums in db.</strong></p> <pre><code>//User model class User &lt; ActiveRecord::Base has_and_belongs_to_many :albums end //Album model class Album &lt; ActiveRecord::Base has_and_belongs_to_many :genres has_and_belongs_to_many :users end //Genre model class Genre &lt; 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 </code></pre> <p>When I send data as follows, data is inserted properly in albums_users. </p> <pre><code>"Album"=&gt;{"title"=&gt;"Test album", "description"=&gt;"test description" </code></pre> <p>However I want insert data into albums_genres table as well. For this, my params data looks like:</p> <pre><code>"Album"=&gt;{"title"=&gt;"Test album", "description"=&gt;"test description", "genre_ids"=&gt;["1", "2", "3"]} </code></pre> <p>Then I got an error <strong>Can't mass-assign protected attributes: genre_ids</strong>. 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: <a href="http://railscasts.com/episodes/17-habtm-checkboxes" rel="nofollow">http://railscasts.com/episodes/17-habtm-checkboxes</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload