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