carts_controller.rb 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. # GET /carts
  11. # GET /carts.json
  12. def index
  13. @carts = Cart.all
  14. respond_to do |format|
  15. format.html # index.html.erb
  16. format.json { render json: @carts }
  17. end
  18. end
  19. # GET /carts/1
  20. # GET /carts/1.json
  21. def show
  22. begin
  23. @cart = Cart.find(params[:id])
  24. rescue ActiveRecord::RecordNotFound
  25. logger.error "Attempt to access invalid cart #{params[:id]}"
  26. redirect_to store_url, notice: 'Invalid cart'
  27. else
  28. respond_to do |format|
  29. format.html # show.html.erb
  30. format.json { render json: @cart }
  31. end
  32. end
  33. end
  34. # GET /carts/new
  35. # GET /carts/new.json
  36. def new
  37. @cart = Cart.new
  38. respond_to do |format|
  39. format.html # new.html.erb
  40. format.json { render json: @cart }
  41. end
  42. end
  43. # GET /carts/1/edit
  44. def edit
  45. @cart = Cart.find(params[:id])
  46. end
  47. # POST /carts
  48. # POST /carts.json
  49. def create
  50. @cart = Cart.new(params[:cart])
  51. respond_to do |format|
  52. if @cart.save
  53. format.html { redirect_to @cart, notice: 'Cart was successfully created.' }
  54. format.json { render json: @cart, status: :created, location: @cart }
  55. else
  56. format.html { render action: "new" }
  57. format.json { render json: @cart.errors, status: :unprocessable_entity }
  58. end
  59. end
  60. end
  61. # PUT /carts/1
  62. # PUT /carts/1.json
  63. def update
  64. @cart = Cart.find(params[:id])
  65. respond_to do |format|
  66. if @cart.update_attributes(params[:cart])
  67. format.html { redirect_to @cart, notice: 'Cart was successfully updated.' }
  68. format.json { head :ok }
  69. else
  70. format.html { render action: "edit" }
  71. format.json { render json: @cart.errors, status: :unprocessable_entity }
  72. end
  73. end
  74. end
  75. # DELETE /carts/1
  76. # DELETE /carts/1.json
  77. def destroy
  78. @cart = current_cart
  79. @cart.destroy
  80. session[:cart_id] = nil
  81. respond_to do |format|
  82. format.html { redirect_to store_url,
  83. notice: 'Your cart is currently empty' }
  84. format.json { head :ok }
  85. end
  86. end
  87. end