Search code examples
ruby-on-rails-4activeadmincancanrolify

Updating Roles in rolify using ActiveAdmin


Using Rails 4.0, ActiveAdmin, Rolify and CanCan, Adding and removing user roles via the activeadmin panel does not save (commit to database).

The my ActiveAdmin User and User Model look okay as I can list all the roles that apply to a user using check_boxes. Although when adding any roles or removing any roles via the checkboxes the changes do not get applied.

enter image description here

I get a notification that the user was updated successfully but as I look through the database or render the page, the roles have not been updated.

How can I get the roles to update when the form is saved?

Edit:

Using Devise also.

enter image description here


Solution

  • The solution here is to allow the ActiveAdmin controller to update the role ids related to the user.

    ActiveAdmin.register User do
    
      permit_params :email, :password, :password_confirmation, role_ids: []
    

    Here's a form that shows a check box for each global role.

      form do |f|
        f.inputs "User Details" do
          f.input :email
          f.input :password
          f.input :password_confirmation
          f.input :roles, as: :check_boxes
        end
        f.actions
      end
    

    While we're at it, we might as well make it possible to update the user without entering their password:

      # Allow form to be submitted without a password
      controller do
        def update
          if params[:user][:password].blank?
            params[:user].delete "password"
            params[:user].delete "password_confirmation"
          end
    
          super
        end
      end
    

    Put all of this in the app/admin/user.rb.