Search code examples
ruby-on-railsrubydevisepundit

Admin Page Ruby on Rails


I created a website with 3 different roles based on Pundit as an enum, users can be an analyst, developer or an administrator.

I have a controller System with an action, users_list .

def users_list
    @users = User.order(:id).page params[:page]
    authorize @users
end

And bellow is my view. def users_list @users = User.order(:id).page params[:page] authorize @users end

<%- model_class = User -%>
<div class="page-header">
  <h1><%=t '.title', :default => model_class.model_name.human.pluralize.titleize %></h1>
</div>
<table class="table table-striped">
  <thead>
    <tr>
      <th><%= model_class.human_attribute_name(:id) %></th>
      <th><%= model_class.human_attribute_name(:email) %></th>
      <th><%= model_class.human_attribute_name(:role) %></th>
      <th><%= model_class.human_attribute_name(:created_at) %></th>
      <th><%=t '.actions', :default => t("helpers.actions") %></th>
    </tr>
  </thead>
  <tbody>
    <% @users.each do |user| %>
      <tr>
        <td><%= link_to user.id, edit_user_registration_path(user) %></td>
        <td><%= user.email %></td>
        <td><%= user.role %></td>
        <td><%=l user.created_at %></td>
        <td>

          <%= link_to t('.destroy', :default => t("helpers.links.destroy")),
                      cancel_user_registration_path(user),
                      :method => :delete,
                      :data => { :confirm => t('.confirm', :default => t("helpers.links.confirm", :default => 'Are you sure?')) },
                      :class => 'btn btn-xs btn-danger' %>
        </td>
      </tr>
    <% end %>
  </tbody>
</table>

<%= link_to t('.new', :default => t("helpers.links.new")),
            new_user_registration_path,
            :class => 'btn btn-primary' %>

What I want to know is how can I enable in this page the administrator to change the user's role.


Solution

  • So, I found the solution for my question, I've created a new action on Users Controller

        class UsersController < ApplicationController
    
      def update
        @user = User.find(params[:id])
        authorize @user
        if @user.update_attributes(secure_params)
          redirect_to controle_sistema_users_list_path, :success => 'User updated'
        else
          redirect_to controle_sistema_users_list_path, :alert => 'Unable to update user'
        end
      end
    
      private
      def secure_params
        params.require(:user).permit(:role)
      end
    end
    

    And created a form inside a td element in the users_list page

    <td>
      <%= form_for(user) do |f| %>
        <%= f.select(:role, User.roles.keys.map {|role| [role.titleize,role]}) %>
        <%= f.submit 'Change Role', :class => "btn btn-default btn-xs" %>
      <%end%>
    </td>