orders_controller.rb 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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 OrdersController < ApplicationController
  10. include CurrentCart
  11. before_action :set_cart, only: [:new, :create]
  12. before_action :set_order, only: [:show, :edit, :update, :destroy]
  13. # GET /orders
  14. # GET /orders.json
  15. def index
  16. @orders = Order.all
  17. end
  18. # GET /orders/1
  19. # GET /orders/1.json
  20. def show
  21. end
  22. # GET /orders/new
  23. def new
  24. if @cart.line_items.empty?
  25. redirect_to store_url, notice: "Your cart is empty"
  26. return
  27. end
  28. @order = Order.new
  29. end
  30. # GET /orders/1/edit
  31. def edit
  32. end
  33. # POST /orders
  34. # POST /orders.json
  35. def create
  36. @order = Order.new(order_params)
  37. @order.add_line_items_from_cart(@cart)
  38. respond_to do |format|
  39. if @order.save
  40. Cart.destroy(session[:cart_id])
  41. session[:cart_id] = nil
  42. format.html { redirect_to store_url, notice:
  43. 'Thank you for your order.' }
  44. format.json { render :show, status: :created,
  45. location: @order }
  46. else
  47. format.html { render :new }
  48. format.json { render json: @order.errors,
  49. status: :unprocessable_entity }
  50. end
  51. end
  52. end
  53. # PATCH/PUT /orders/1
  54. # PATCH/PUT /orders/1.json
  55. def update
  56. respond_to do |format|
  57. if @order.update(order_params)
  58. format.html { redirect_to @order, notice: 'Order was successfully updated.' }
  59. format.json { render :show, status: :ok, location: @order }
  60. else
  61. format.html { render :edit }
  62. format.json { render json: @order.errors, status: :unprocessable_entity }
  63. end
  64. end
  65. end
  66. # DELETE /orders/1
  67. # DELETE /orders/1.json
  68. def destroy
  69. @order.destroy
  70. respond_to do |format|
  71. format.html { redirect_to orders_url, notice: 'Order was successfully destroyed.' }
  72. format.json { head :no_content }
  73. end
  74. end
  75. private
  76. # Use callbacks to share common setup or constraints between actions.
  77. def set_order
  78. @order = Order.find(params[:id])
  79. end
  80. # Never trust parameters from the scary internet, only allow the white list through.
  81. def order_params
  82. params.require(:order).permit(:name, :address, :email, :pay_type)
  83. end
  84. #...
  85. end