/app/controllers/admin/users_controller.rb

https://github.com/brunofacca/zen-rails-base-app · Ruby · 97 lines · 59 code · 16 blank · 22 comment · 6 complexity · e7d4438e8a49587fcb7ffab60c294495 MD5 · raw file

  1. module Admin
  2. # This controller is for admin use only (user management by admins). The form
  3. # provided by Devise's registerable module (which allows users to edit their
  4. # profiles) uses another controller.
  5. class UsersController < ApplicationController
  6. helper UsersHelper
  7. before_action :set_user, only: %i[show edit update destroy]
  8. # This hack is required to use Pundit with a namespaced controller
  9. def self.policy_class
  10. Admin::UserPolicy
  11. end
  12. # GET /admin/users
  13. def index
  14. # This ivar is not used in the view, only as input to Ransack. There is
  15. # no need to eager load associations here, Ransack avoids N+1 queries.
  16. @q = policy_scope(User).ransack(params[:q])
  17. # Ransack default (initial) sort order
  18. @q.sorts = 'full_name asc' if @q.sorts.empty?
  19. # Ransack search/filter results, paginated by Kaminari.
  20. @users = @q.result.page(params[:page])
  21. end
  22. # GET /admin/users/1
  23. def show
  24. authorize @user
  25. end
  26. # GET /admin/users/new
  27. def new
  28. @user = User.new
  29. authorize @user
  30. end
  31. # GET /admin/users/1/edit
  32. def edit
  33. authorize @user
  34. end
  35. # POST /admin/users
  36. def create
  37. @user = User.new(user_params)
  38. authorize @user
  39. if @user.save
  40. redirect_to [:admin, @user], notice: t('.success')
  41. else
  42. render :new
  43. end
  44. end
  45. # PATCH/PUT /admin/users/1
  46. def update
  47. authorize @user
  48. # Allow updating the user without changing its password (password field
  49. # will be blank). Remove the password key of the params hash if it's blank
  50. # (avoid validation error).
  51. if params[:user][:password].blank?
  52. params[:user].delete(:password)
  53. params[:user].delete(:password_confirmation)
  54. end
  55. if @user.update(user_params)
  56. # If the user is editing himself, Devise will automatically logout.
  57. # To avoid asking the user to login, we'll login automatically here.
  58. bypass_sign_in(@user) if current_user == @user
  59. redirect_to [:admin, @user], notice: t('.success')
  60. else
  61. render :edit
  62. end
  63. end
  64. # DELETE /admin/users/1
  65. def destroy
  66. authorize @user
  67. @user.destroy
  68. redirect_to admin_users_url, notice: t('.success')
  69. end
  70. private
  71. # Use callbacks to share common setup or constraints between actions.
  72. def set_user
  73. @user = User.friendly.find(params[:id])
  74. end
  75. # Strong parameters
  76. def user_params
  77. params.require(:user).permit(:email, :password, :password_confirmation,
  78. :role, :first_name, :last_name)
  79. end
  80. end
  81. end