users_controller.rb 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. class UsersController < ApplicationController
  2. before_action :set_user, only: [:show, :edit, :update, :destroy, :courses]
  3. before_action :check_permission, only: [:edit, :update]
  4. def index
  5. respond_to do |format|
  6. @users = current_user.school ? current_user.school.users : User.all
  7. format.json
  8. format.html
  9. end
  10. end
  11. def show
  12. end
  13. def new
  14. end
  15. def edit
  16. end
  17. def update
  18. if @user.update(user_params)
  19. flash[:success] = 'Profile updated'
  20. redirect_to @user
  21. else
  22. render :edit
  23. end
  24. end
  25. def courses
  26. @title = "#{@user.name.possessive} courses"
  27. @courses = @user.courses
  28. render 'show_courses'
  29. end
  30. private
  31. # Use callbacks to share common setup or constraints between actions.
  32. def set_user
  33. @user = User.find(params[:id])
  34. end
  35. # Only allow certain attributes to be updated over the web.
  36. def user_params
  37. allowed = [:login, :email, :password, :password_confirmation,
  38. :phone, :picture]
  39. if can_administer?
  40. allowed += [:gender, :birth_date, :name]
  41. end
  42. if current_user.admin?
  43. allowed += [:admin]
  44. end
  45. params.require(:user).permit(*allowed)
  46. end
  47. # Confirms the correct user.
  48. def check_permission
  49. redirect_to(root_url) unless can_edit?
  50. end
  51. def can_edit?
  52. current_user?(@user) || can_administer?
  53. end
  54. def can_administer?
  55. current_user.is_administrator_at?(@user.school) || current_user.admin?
  56. end
  57. end