/chapter_3/shop/app/controllers/products_controller.rb

https://github.com/liwei78/rails-practice-code · Ruby · 87 lines · 60 code · 12 blank · 15 comment · 3 complexity · 9afb5b9f0301db22f48563a4def7e0d2 MD5 · raw file

  1. class ProductsController < ApplicationController
  2. # Authentication, except index, show
  3. skip_before_action :authenticate_user!, only: [:index, :show]
  4. before_action :set_product, only: [:show, :edit, :update, :destroy]
  5. # GET /products
  6. # GET /products.json
  7. def index
  8. @q = Product.ransack(params[:q])
  9. @q.sorts = 'id desc' if @q.sorts.empty?
  10. @products = @q.result(distinct: true)
  11. @product = Product.new
  12. end
  13. # GET /products/1
  14. # GET /products/1.json
  15. def show
  16. end
  17. # GET /products/new
  18. def new
  19. @product = Product.new
  20. end
  21. # GET /products/1/edit
  22. def edit
  23. respond_to do |format|
  24. format.html
  25. format.json { render json: @product, status: :ok, location: @product }
  26. end
  27. end
  28. # POST /products
  29. # POST /products.json
  30. def create
  31. @product = Product.new(product_params)
  32. respond_to do |format|
  33. if @product.save
  34. format.html { redirect_to @product, notice: 'Product was successfully created.' }
  35. format.json { render :show, status: :created, location: @product }
  36. else
  37. format.html { render :new }
  38. format.json { render json: @product.errors, status: :unprocessable_entity }
  39. end
  40. format.js
  41. end
  42. end
  43. # PATCH/PUT /products/1
  44. # PATCH/PUT /products/1.json
  45. def update
  46. respond_to do |format|
  47. if @product.update(product_params)
  48. format.html { redirect_to @product, notice: 'Product was successfully updated.' }
  49. format.json
  50. else
  51. format.html { render :edit }
  52. format.json { render json: @product.errors.full_messages.join(', '), status: :error }
  53. end
  54. end
  55. end
  56. # DELETE /products/1
  57. # DELETE /products/1.json
  58. def destroy
  59. @product.destroy
  60. respond_to do |format|
  61. format.html { redirect_to products_url, notice: 'Product was successfully destroyed.' }
  62. format.json { head :no_content }
  63. format.js
  64. end
  65. end
  66. private
  67. # Use callbacks to share common setup or constraints between actions.
  68. def set_product
  69. @product = Product.find(params[:id])
  70. end
  71. # Never trust parameters from the scary internet, only allow the white list through.
  72. def product_params
  73. params.require(:product).permit(:name, :price, :description)
  74. end
  75. end