Nested checkbox object - bulk assignment even with accepts_nested_attributes_for?

I thought there should have been a simple solution to this, given that Rails 2.3 has this newfangled nested form. Basically I want to create or update a user and assign them roles at the same time.

It seems that I am doing everything right, but I am getting the WARNING error message . You cannot assign these protected attributes: role_attrributes .

I even tried changing the view to the user [permissions_attrributes] [role_id], because I thought that perhaps the connection table was confusing Rails.

Anyway, any suggestions on how this should work?

Model

class User < ActiveRecord::Base has_many :permissions has_many :roles, :through => :permissions accepts_nested_attributes_for :roles accepts_nested_attributes_for :permissions end 

Excerpt from view (notification I tried and could not get fields_for to generate what I want here, maybe my problem?)

 <% for role in Role.all %> <%= check_box_tag( "user[roles_attrributes][id]",role.id) %> <%= role.rolename %> <br/> <% end %> 

Paramas that seem correct:

  {"user"=>{"password_confirmation"=>"[FILTERED]", "roles_attrributes"=>{"id"=>"2"}, ... 

Solution . The combination of me with a misspelling error, not using attr_accessible, requiring access to attribute privileges, and the form is slightly debugged.

Model:

 has_many :permissions, :dependent => :destroy has_many :roles, :through => :permissions accepts_nested_attributes_for :permissions attr_accessible :permissions_attributes 

View:

  <% Role.all(:order => "rolename ASC").each_with_index do |role,idx| %> <%= check_box_tag( "user[permissions_attributes][#{idx}][role_id]",role.id) %> <%= role.rolename %> <br/> <% end %> 
+7
ruby-on-rails activerecord associations actionview
source share
2 answers

this attribute does not seem to be marked as safe for updating. You can fix this by adding the following to the model class:

 attr_accessible :roles 

or perhaps:

 attr_accessible :roles_attributes 

If you look, you may already have an attr_accessible call available to which you can add this. For more information, this is described here:

http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002226

+3
source share

If you correct the spelling of the attributes in check_box_tag , it looks like it should work.

 <% for role in Role.all %> <%= check_box_tag( "user[roles_attributes][id]",role.id) %> <%= role.rolename %> <br/> <% end %> 
+5
source share

All Articles