line_items_controller.rb 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 LineItemsController < ApplicationController
  10. include CurrentCart
  11. before_action :set_cart, only: [:create]
  12. before_action :set_line_item, only: [:show, :edit, :update, :destroy]
  13. # GET /line_items
  14. # GET /line_items.json
  15. def index
  16. @line_items = LineItem.all
  17. end
  18. # GET /line_items/1
  19. # GET /line_items/1.json
  20. def show
  21. end
  22. # GET /line_items/new
  23. def new
  24. @line_item = LineItem.new
  25. end
  26. # GET /line_items/1/edit
  27. def edit
  28. end
  29. # POST /line_items
  30. # POST /line_items.json
  31. def create
  32. product = Product.find(params[:product_id])
  33. @line_item = @cart.add_product(product.id)
  34. respond_to do |format|
  35. if @line_item.save
  36. format.html { redirect_to store_url }
  37. format.js
  38. format.json { render :show,
  39. status: :created, location: @line_item }
  40. else
  41. format.html { render :new }
  42. format.json { render json: @line_item.errors,
  43. status: :unprocessable_entity }
  44. end
  45. end
  46. end
  47. # PATCH/PUT /line_items/1
  48. # PATCH/PUT /line_items/1.json
  49. def update
  50. respond_to do |format|
  51. if @line_item.update(line_item_params)
  52. format.html { redirect_to @line_item, notice: 'Line item was successfully updated.' }
  53. format.json { render :show, status: :ok, location: @line_item }
  54. else
  55. format.html { render :edit }
  56. format.json { render json: @line_item.errors, status: :unprocessable_entity }
  57. end
  58. end
  59. end
  60. # DELETE /line_items/1
  61. # DELETE /line_items/1.json
  62. def destroy
  63. @line_item.destroy
  64. respond_to do |format|
  65. format.html { redirect_to line_items_url, notice: 'Line item was successfully destroyed.' }
  66. format.json { head :no_content }
  67. end
  68. end
  69. private
  70. # Use callbacks to share common setup or constraints between actions.
  71. def set_line_item
  72. @line_item = LineItem.find(params[:id])
  73. end
  74. # Never trust parameters from the scary internet, only allow the white
  75. # list through.
  76. def line_item_params
  77. params.require(:line_item).permit(:product_id)
  78. end
  79. #...
  80. end