line_items_controller.rb 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. @line_item.product = product
  48. respond_to do |format|
  49. if @line_item.save
  50. format.html { redirect_to store_url }
  51. format.js { @current_item = @line_item }
  52. format.json { render json: @line_item,
  53. status: :created, location: @line_item }
  54. else
  55. format.html { render action: "new" }
  56. format.json { render json: @line_item.errors,
  57. status: :unprocessable_entity }
  58. end
  59. end
  60. end
  61. # PUT /line_items/1
  62. # PUT /line_items/1.json
  63. def update
  64. @line_item = LineItem.find(params[:id])
  65. respond_to do |format|
  66. if @line_item.update_attributes(params[:line_item])
  67. format.html { redirect_to @line_item, notice: 'Line item was successfully updated.' }
  68. format.json { head :no_content }
  69. else
  70. format.html { render action: "edit" }
  71. format.json { render json: @line_item.errors, status: :unprocessable_entity }
  72. end
  73. end
  74. end
  75. # DELETE /line_items/1
  76. # DELETE /line_items/1.json
  77. def destroy
  78. @line_item = LineItem.find(params[:id])
  79. @line_item.destroy
  80. respond_to do |format|
  81. format.html { redirect_to line_items_url }
  82. format.json { head :no_content }
  83. end
  84. end
  85. end