I’m using the code from Railscasts 189 to implement roles with Devise so I can use Cancan. However the roles are not being saved to the role_mask field. Relevant code from my user model:
attr_accessible :email, :password, :password_confirmation, :remember_me,
:name, :about, :awards, :url, :roles_mask
ROLES = %w[admin support worker monitor visitor]
named_scope :with_role, lambda { |role| {:conditions => "roles_mask & #{2**ROLES.index(role.to_s)} > 0"} }
def roles=(roles)
self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.sum
end
def roles
ROLES.reject { |r| ((roles_mask || 0) & 2**ROLES.index(r)).zero? }
end
def role_symbols
roles.map(&:to_sym)
end
In the views for user “new” and “edit” I have the following to show checkboxes for the roles:
<p>
<%= f.label :roles %><br />
<% for role in User::ROLES %>
<%= check_box_tag "user[roles][]", role, @user.roles.include?(role) %>
<%=h role.humanize %><br />
<% end %>
<%= hidden_field_tag "user[roles][]", "" %>
</p>
When I check the check boxes for a couple of the roles and hit “submit”, I get the following flash:
1 error prohibited this user from being saved:
And I get the following error from the server:
WARNING: Can’t mass-assign protected attributes: roles
I’ve checked the DB and nothing gets saved in the roles_mask field. There are lots of questions in Stackoverflow about “can’t mass-assign protected attributes” but they don’t seem germane to this situation.
Any suggestions?
Try adding :roles to the attr_accessible list like this:
Understand completely about the mass-assignment issues before doing this.