1 #--- 2 # Excerpted from "Agile Web Development with Rails, 3rd Ed.", 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/rails3 for more book information. 8 #--- 9 class UsersController < ApplicationController 10 # GET /users 11 # GET /users.xml 12 def index 13 @users = User.find(:all, :order => :name) 14 15 respond_to do |format| 16 format.html # index.html.erb 17 format.xml { render :xml => @users } 18 end 19 end 20 21 # GET /users/1 22 # GET /users/1.xml 23 def show 24 @user = User.find(params[:id]) 25 26 respond_to do |format| 27 format.html # show.html.erb 28 format.xml { render :xml => @user } 29 end 30 end 31 32 # GET /users/new 33 # GET /users/new.xml 34 def new 35 @user = User.new 36 37 respond_to do |format| 38 format.html # new.html.erb 39 format.xml { render :xml => @user } 40 end 41 end 42 43 # GET /users/1/edit 44 def edit 45 @user = User.find(params[:id]) 46 end 47 48 # POST /users 49 # POST /users.xml 50 def create 51 @user = User.new(params[:user]) 52 53 respond_to do |format| 54 if @user.save 55 flash[:notice] = "User #{@user.name} was successfully created." 56 format.html { redirect_to(:action=>'index') } 57 format.xml { render :xml => @user, :status => :created, 58 :location => @user } 59 else 60 format.html { render :action => "new" } 61 format.xml { render :xml => @user.errors, 62 :status => :unprocessable_entity } 63 end 64 end 65 end 66 67 # PUT /users/1 68 # PUT /users/1.xml 69 def update 70 @user = User.find(params[:id]) 71 72 respond_to do |format| 73 if @user.update_attributes(params[:user]) 74 flash[:notice] = "User #{@user.name} was successfully updated." 75 format.html { redirect_to(:action=>'index') } 76 format.xml { head :ok } 77 else 78 format.html { render :action => "edit" } 79 format.xml { render :xml => @user.errors, 80 :status => :unprocessable_entity } 81 end 82 end 83 end 84 85 # DELETE /users/1 86 # DELETE /users/1.xml 87 88 def destroy 89 @user = User.find(params[:id]) 90 begin 91 @user.destroy 92 flash[:notice] = "User #{@user.name} deleted" 93 rescue Exception => e 94 flash[:notice] = e.message 95 end 96 97 respond_to do |format| 98 format.html { redirect_to(users_url) } 99 format.xml { head :ok } 100 end 101 102 end 103 end