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 ProductsController < ApplicationController 10 # GET /products 11 # GET /products.xml 12 def index 13 @products = Product.find(:all) 14 15 respond_to do |format| 16 format.html # index.html.erb 17 format.xml { render :xml => @products } 18 end 19 end 20 21 # GET /products/1 22 # GET /products/1.xml 23 def show 24 @product = Product.find(params[:id]) 25 26 respond_to do |format| 27 format.html # show.html.erb 28 format.xml { render :xml => @product } 29 end 30 end 31 32 # GET /products/new 33 # GET /products/new.xml 34 def new 35 @product = Product.new 36 37 respond_to do |format| 38 format.html # new.html.erb 39 format.xml { render :xml => @product } 40 end 41 end 42 43 # GET /products/1/edit 44 def edit 45 @product = Product.find(params[:id]) 46 end 47 48 # POST /products 49 # POST /products.xml 50 def create 51 @product = Product.new(params[:product]) 52 53 respond_to do |format| 54 if @product.save 55 flash[:notice] = 'Product was successfully created.' 56 format.html { redirect_to(@product) } 57 format.xml { render :xml => @product, :status => :created, :location => @product } 58 else 59 format.html { render :action => "new" } 60 format.xml { render :xml => @product.errors, :status => :unprocessable_entity } 61 end 62 end 63 end 64 65 # PUT /products/1 66 # PUT /products/1.xml 67 def update 68 @product = Product.find(params[:id]) 69 70 respond_to do |format| 71 if @product.update_attributes(params[:product]) 72 flash[:notice] = 'Product was successfully updated.' 73 format.html { redirect_to(@product) } 74 format.xml { head :ok } 75 else 76 format.html { render :action => "edit" } 77 format.xml { render :xml => @product.errors, :status => :unprocessable_entity } 78 end 79 end 80 end 81 82 # DELETE /products/1 83 # DELETE /products/1.xml 84 def destroy 85 @product = Product.find(params[:id]) 86 @product.destroy 87 88 respond_to do |format| 89 format.html { redirect_to(products_url) } 90 format.xml { head :ok } 91 end 92 end 93 end