products_controller.rb 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. class ProductsController < ApplicationController
  2. before_action :set_product, only: %i[ show edit update destroy ]
  3. # GET /products or /products.json
  4. def index
  5. @products = Product.all
  6. end
  7. # GET /products/1 or /products/1.json
  8. def show
  9. end
  10. # GET /products/new
  11. def new
  12. @product = Product.new
  13. end
  14. # GET /products/1/edit
  15. def edit
  16. end
  17. # POST /products or /products.json
  18. def create
  19. @product = Product.new(product_params)
  20. respond_to do |format|
  21. if @product.save
  22. format.html { redirect_to @product, notice: "Product was successfully created." }
  23. format.json { render :show, status: :created, location: @product }
  24. else
  25. format.html { render :new, status: :unprocessable_entity }
  26. format.json { render json: @product.errors, status: :unprocessable_entity }
  27. end
  28. end
  29. end
  30. # PATCH/PUT /products/1 or /products/1.json
  31. def update
  32. respond_to do |format|
  33. if @product.update(product_params)
  34. format.html { redirect_to @product, notice: "Product was successfully updated.", status: :see_other }
  35. format.json { render :show, status: :ok, location: @product }
  36. else
  37. format.html { render :edit, status: :unprocessable_entity }
  38. format.json { render json: @product.errors, status: :unprocessable_entity }
  39. end
  40. end
  41. end
  42. # DELETE /products/1 or /products/1.json
  43. def destroy
  44. @product.destroy!
  45. respond_to do |format|
  46. format.html { redirect_to products_path, notice: "Product was successfully destroyed.", status: :see_other }
  47. format.json { head :no_content }
  48. end
  49. end
  50. private
  51. # Use callbacks to share common setup or constraints between actions.
  52. def set_product
  53. @product = Product.find(params.expect(:id))
  54. end
  55. # Only allow a list of trusted parameters through.
  56. def product_params
  57. params.expect(product: [ :title, :description, :image, :price ])
  58. end
  59. end