products_controller.rb 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. before_action :set_product, only: [:show, :edit, :update, :destroy]
  11. # GET /products
  12. # GET /products.json
  13. def index
  14. @products = Product.all
  15. end
  16. # GET /products/1
  17. # GET /products/1.json
  18. def show
  19. end
  20. # GET /products/new
  21. def new
  22. @product = Product.new
  23. end
  24. # GET /products/1/edit
  25. def edit
  26. end
  27. # POST /products
  28. # POST /products.json
  29. def create
  30. @product = Product.new(product_params)
  31. respond_to do |format|
  32. if @product.save
  33. format.html { redirect_to @product,
  34. notice: 'Product was successfully created.' }
  35. format.json { render :show, status: :created,
  36. location: @product }
  37. else
  38. format.html { render :new }
  39. format.json { render json: @product.errors,
  40. status: :unprocessable_entity }
  41. end
  42. end
  43. end
  44. # PATCH/PUT /products/1
  45. # PATCH/PUT /products/1.json
  46. def update
  47. respond_to do |format|
  48. if @product.update(product_params)
  49. format.html { redirect_to @product,
  50. notice: 'Product was successfully updated.' }
  51. format.json { render :show, status: :ok, location: @product }
  52. else
  53. format.html { render :edit }
  54. format.json { render json: @product.errors,
  55. status: :unprocessable_entity }
  56. end
  57. end
  58. end
  59. # DELETE /products/1
  60. # DELETE /products/1.json
  61. def destroy
  62. @product.destroy
  63. respond_to do |format|
  64. format.html { redirect_to products_url,
  65. notice: 'Product was successfully destroyed.' }
  66. format.json { head :no_content }
  67. end
  68. end
  69. private
  70. # Use callbacks to share common setup or constraints between actions.
  71. def set_product
  72. @product = Product.find(params[:id])
  73. end
  74. # Never trust parameters from the scary internet, only allow the white
  75. # list through.
  76. def product_params
  77. params.require(:product).permit(:title, :description, :image_url, :price)
  78. end
  79. end