diff --git a/app/controllers/orders_controller.rb b/app/controllers/orders_controller.rb index 1bb10fc..b910205 100644 --- a/app/controllers/orders_controller.rb +++ b/app/controllers/orders_controller.rb @@ -22,6 +22,8 @@ def create end if @order.save + # Orderレコード作成時に、カートとのリレーションの作成、商品の在庫数更新を行う + decrease_product_stock(cart_products: @cart_products) session[:cart_id] = nil flash[:success] = '購入ありがとうございます' OrderMailer.complete(order: @order).deliver_later @@ -43,6 +45,14 @@ def set_cart_products @total = @cart_products.inject(0) { |total, cart_product| total + cart_product.subtotal } end + def decrease_product_stock(cart_products:) + cart_products.each do |cart_product| + product = Product.find(cart_product.product_id) + quantity = cart_product.quantity + Product.update(cart_product.product_id, stock: product.stock - quantity) + end + end + def out_of_stock?(cart_products:) cart_products.each do |cart_product| product = Product.find(cart_product.product_id)