carts_controller.rb 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 CartsController < ApplicationController
  10. before_action :set_cart, only: [:show, :edit, :update, :destroy]
  11. rescue_from ActiveRecord::RecordNotFound, with: :invalid_cart
  12. # GET /carts
  13. # GET /carts.json
  14. def index
  15. @carts = Cart.all
  16. end
  17. # GET /carts/1
  18. # GET /carts/1.json
  19. def show
  20. end
  21. # GET /carts/new
  22. def new
  23. @cart = Cart.new
  24. end
  25. # GET /carts/1/edit
  26. def edit
  27. end
  28. # POST /carts
  29. # POST /carts.json
  30. def create
  31. @cart = Cart.new(cart_params)
  32. respond_to do |format|
  33. if @cart.save
  34. format.html { redirect_to @cart, notice: 'Cart was successfully created.' }
  35. format.json { render :show, status: :created, location: @cart }
  36. else
  37. format.html { render :new }
  38. format.json { render json: @cart.errors, status: :unprocessable_entity }
  39. end
  40. end
  41. end
  42. # PATCH/PUT /carts/1
  43. # PATCH/PUT /carts/1.json
  44. def update
  45. respond_to do |format|
  46. if @cart.update(cart_params)
  47. format.html { redirect_to @cart, notice: 'Cart was successfully updated.' }
  48. format.json { render :show, status: :ok, location: @cart }
  49. else
  50. format.html { render :edit }
  51. format.json { render json: @cart.errors, status: :unprocessable_entity }
  52. end
  53. end
  54. end
  55. # DELETE /carts/1
  56. # DELETE /carts/1.json
  57. def destroy
  58. @cart.destroy if @cart.id == session[:cart_id]
  59. session[:cart_id] = nil
  60. respond_to do |format|
  61. format.html { redirect_to store_url,
  62. notice: 'Your cart is currently empty' }
  63. format.json { head :no_content }
  64. end
  65. end
  66. # ...
  67. private
  68. # ...
  69. def set_cart
  70. @cart = Cart.find(params[:id])
  71. end
  72. # Never trust parameters from the scary internet, only allow the white list through.
  73. def cart_params
  74. params[:cart]
  75. end
  76. def invalid_cart
  77. logger.error "Attempt to access invalid cart #{params[:id]}"
  78. redirect_to store_url, notice: 'Invalid cart'
  79. end
  80. end