line_items_controller.rb 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. # GET /line_items
  11. # GET /line_items.json
  12. def index
  13. @line_items = LineItem.all
  14. respond_to do |format|
  15. format.html # index.html.erb
  16. format.json { render json: @line_items }
  17. end
  18. end
  19. # GET /line_items/1
  20. # GET /line_items/1.json
  21. def show
  22. @line_item = LineItem.find(params[:id])
  23. respond_to do |format|
  24. format.html # show.html.erb
  25. format.json { render json: @line_item }
  26. end
  27. end
  28. # GET /line_items/new
  29. # GET /line_items/new.json
  30. def new
  31. @line_item = LineItem.new
  32. respond_to do |format|
  33. format.html # new.html.erb
  34. format.json { render json: @line_item }
  35. end
  36. end
  37. # GET /line_items/1/edit
  38. def edit
  39. @line_item = LineItem.find(params[:id])
  40. end
  41. # POST /line_items
  42. # POST /line_items.json
  43. def create
  44. @cart = current_cart
  45. product = Product.find(params[:product_id])
  46. @line_item = @cart.add_product(product.id)
  47. respond_to do |format|
  48. if @line_item.save
  49. format.html { redirect_to @line_item.cart }
  50. format.json { render json: @line_item,
  51. status: :created, location: @line_item }
  52. else
  53. format.html { render action: "new" }
  54. format.json { render json: @line_item.errors,
  55. status: :unprocessable_entity }
  56. end
  57. end
  58. end
  59. # PUT /line_items/1
  60. # PUT /line_items/1.json
  61. def update
  62. @line_item = LineItem.find(params[:id])
  63. respond_to do |format|
  64. if @line_item.update_attributes(params[:line_item])
  65. format.html { redirect_to @line_item, notice: 'Line item was successfully updated.' }
  66. format.json { head :ok }
  67. else
  68. format.html { render action: "edit" }
  69. format.json { render json: @line_item.errors, status: :unprocessable_entity }
  70. end
  71. end
  72. end
  73. # DELETE /line_items/1
  74. # DELETE /line_items/1.json
  75. def destroy
  76. @line_item = LineItem.find(params[:id])
  77. @line_item.destroy
  78. respond_to do |format|
  79. format.html { redirect_to line_items_url }
  80. format.json { head :ok }
  81. end
  82. end
  83. end