products_controller.rb 2.4 KB

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