class UsersController < ApplicationController before_action :authenticate_user! before_action :require_admin before_action :set_user, only: [:show, :edit, :update, :destroy] load_and_authorize_resource def create @user = User.new(user_params) if @user.save redirect_to users_path, notice: 'User was successfully created.' else render :new end end def edit # Since @user is set by set_user, there's no need to find the user again end def update # Clean up password fields if they are blank cleaned_params = user_params if cleaned_params[:password].blank? cleaned_params.delete(:password) cleaned_params.delete(:password_confirmation) end # Attempt to update the user with the cleaned parameters if @user.update(cleaned_params) UserRoleService.new(@user, params[:user][:roles] || []).update_roles # Handle roles separately redirect_to users_path, notice: 'User was successfully updated.' else render :edit # If there's an error, it will render the edit view where you can display error messages end end def destroy @user.destroy redirect_to users_path, notice: 'User was successfully deleted.' end private def set_user @user = User.find(params[:id]) end def user_params params.require(:user).permit( :email, :password, :password_confirmation, :remember_me, :first_name, :last_name, :phone, :company, :access_revoked, :access_start_date, :access_end_date, access_periods_attributes: [:id, :start_date, :end_date, :_destroy], ) end def require_admin redirect_to root_path, alert: 'Only admins are allowed to access this section.' unless current_user.admin? end end