Note that there are some explanatory texts on larger screens.

plurals
  1. PONested Object w/ Checkboxes - mass-assignment even with accepts_nested_attributes_for?
    text
    copied!<p>I thought that there should have been a simple solution to this, given that Rails 2.3 has this newfangled nested forms feature. Basically I want to create or update a user and assign them roles at the same time.</p> <p>It seems like I'm doing everything right but I get the error <strong>WARNING: Can't mass-assign these protected attributes: roles_attrributes</strong>.</p> <p>I even tried changing the view to user[permissions_attrributes][role_id] because I thought that maybe the join table was confusing Rails. </p> <p>Anyways, any suggestions on how this should actually work?</p> <p>Model</p> <pre><code>class User &lt; ActiveRecord::Base has_many :permissions has_many :roles, :through =&gt; :permissions accepts_nested_attributes_for :roles accepts_nested_attributes_for :permissions end </code></pre> <p>Excerpt from view (notice I tried and failed to get fields_for to generate what I want here, maybe that's my problem?) </p> <pre><code>&lt;% for role in Role.all %&gt; &lt;%= check_box_tag( "user[roles_attrributes][id]",role.id) %&gt; &lt;%= role.rolename %&gt; &lt;br/&gt; &lt;% end %&gt; </code></pre> <p>Params coming across seem to be right:</p> <pre><code> {"user"=&gt;{"password_confirmation"=&gt;"[FILTERED]", "roles_attrributes"=&gt;{"id"=&gt;"2"}, ... </code></pre> <p><strong>Solution</strong> A combination of me misspelling, not using attr_accessible, needing to access permissions_attributes, and the form being slightly off. </p> <p>Model:</p> <pre><code>has_many :permissions, :dependent =&gt; :destroy has_many :roles, :through =&gt; :permissions accepts_nested_attributes_for :permissions attr_accessible :permissions_attributes </code></pre> <p>View:</p> <pre><code> &lt;% Role.all(:order =&gt; "rolename ASC").each_with_index do |role,idx| %&gt; &lt;%= check_box_tag( "user[permissions_attributes][#{idx}][role_id]",role.id) %&gt; &lt;%= role.rolename %&gt; &lt;br/&gt; &lt;% end %&gt; </code></pre>
 

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