carts_controller.rb 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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 :no_content }
  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 :no_content }
  85. end
  86. end
  87. end