line_items_controller.rb 2.5 KB

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