users_controller.rb 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #---
  2. # Excerpted from "Agile Web Development with Rails",
  3. # published by The Pragmatic Bookshelf.
  4. # Copyrights apply to this code. It may not be used to create training material,
  5. # courses, books, articles, and the like. Contact us if you are in doubt.
  6. # We make no guarantees that this code is fit for any purpose.
  7. # Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
  8. #---
  9. class UsersController < ApplicationController
  10. # GET /users
  11. # GET /users.json
  12. def index
  13. @users = User.order(:name)
  14. respond_to do |format|
  15. format.html # index.html.erb
  16. format.json { render json: @users }
  17. end
  18. end
  19. # GET /users/1
  20. # GET /users/1.json
  21. def show
  22. @user = User.find(params[:id])
  23. respond_to do |format|
  24. format.html # show.html.erb
  25. format.json { render json: @user }
  26. end
  27. end
  28. # GET /users/new
  29. # GET /users/new.json
  30. def new
  31. @user = User.new
  32. respond_to do |format|
  33. format.html # new.html.erb
  34. format.json { render json: @user }
  35. end
  36. end
  37. # GET /users/1/edit
  38. def edit
  39. @user = User.find(params[:id])
  40. end
  41. # POST /users
  42. # POST /users.json
  43. def create
  44. @user = User.new(params[:user])
  45. respond_to do |format|
  46. if @user.save
  47. format.html { redirect_to users_url,
  48. notice: "User #{@user.name} was successfully created." }
  49. format.json { render json: @user,
  50. status: :created, location: @user }
  51. else
  52. format.html { render action: "new" }
  53. format.json { render json: @user.errors,
  54. status: :unprocessable_entity }
  55. end
  56. end
  57. end
  58. # PUT /users/1
  59. # PUT /users/1.json
  60. def update
  61. @user = User.find(params[:id])
  62. respond_to do |format|
  63. if @user.update_attributes(params[:user])
  64. format.html { redirect_to users_url,
  65. notice: "User #{@user.name} was successfully updated." }
  66. format.json { head :no_content }
  67. else
  68. format.html { render action: "edit" }
  69. format.json { render json: @user.errors,
  70. status: :unprocessable_entity }
  71. end
  72. end
  73. end
  74. # DELETE /users/1
  75. # DELETE /users/1.json
  76. def destroy
  77. @user = User.find(params[:id])
  78. begin
  79. @user.destroy
  80. flash[:notice] = "User #{@user.name} deleted"
  81. rescue Exception => e
  82. flash[:notice] = e.message
  83. end
  84. respond_to do |format|
  85. format.html { redirect_to users_url }
  86. format.json { head :no_content }
  87. end
  88. end
  89. end