Search code examples
ruby-on-railsrubydevisesimple-formcancan

Using Role Model and simple_forms to assign roles


First off, I am using Devise, Cancan, Role Model, and simple_form. Everything seems to work with permissions and whatnot. What I can't seem to do is create a form so that I can assign roles to Users.

Here is what I have so far:

<%= simple_form_for(@profile.user) do |f| %>
<%= f.input :roles_mask, as: :check_boxes, collection: User.valid_roles, :checked => [ 'member' , true] %>
<%= f.button :submit %>

This shows the check boxes properly, and the last part flags one as true. I'm not sure how to get it to flag the roles that are supposed to be flagged. I chose one at random for testing Also, if I send it to update, nothing seems to happen. I updated like I normally would limiting my params to just the roles_mask variable.

def update
if @user.update(params.require(:user).permit(:roles_mask))
    flash[:notice] = "Permissions updated."
    redirect_to profile_path(@user.profile_id)
else
    render 'edit'
end

I have no clue what I am doing wrong. Even if I could just get them to update. Not showing the current roles isn't a huge deal.


Solution

  • You don't need to directly access roles_mask property, just assign roles property with the array of roles. Example:

    = f.input :roles, collection: User.valid_roles, as: :check_boxes, checked: @user.roles, label_method: proc {|l| User.human_attribute_name(l) } 
    

    And don't forget to permit that form value for strong parameters:

    params.require(:user).permit(roles: [])