carts_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 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 action: 'show', status: :created, location: @cart }
  36. else
  37. format.html { render action: '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 { head :no_content }
  49. else
  50. format.html { render action: '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. format.json { head :no_content }
  63. end
  64. end
  65. # ...
  66. private
  67. # ...
  68. def set_cart
  69. @cart = Cart.find(params[:id])
  70. end
  71. # Never trust parameters from the scary internet, only allow the white list through.
  72. def cart_params
  73. params[:cart]
  74. end
  75. def invalid_cart
  76. logger.error "Attempt to access invalid cart #{params[:id]}"
  77. redirect_to store_url, notice: 'Invalid cart'
  78. end
  79. end