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.
It seems like I'm doing everything right but I get the error WARNING: Can't mass-assign these protected attributes: roles_attrributes.
I even tried changing the view to user[permissions_attrributes][role_id] because I thought that maybe the join table was confusing Rails.
Anyways, any suggestions on how this should actually 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 (notice I tried and failed to get fields_for to generate what I want here, maybe that's my problem?)
<% for role in Role.all %>
<%= check_box_tag( "user[roles_attrributes][id]",role.id) %>
<%= role.rolename %>
<br/>
<% end %>
Params coming across seem to be right:
{"user"=>{"password_confirmation"=>"[FILTERED]",
"roles_attrributes"=>{"id"=>"2"}, ...
Solution A combination of me misspelling, not using attr_accessible, needing to access permissions_attributes, and the form being slightly off.
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 %>