【问题标题】:Updating in stock quantity based on shopping cart quantity in rails app?根据rails应用程序中的购物车数量更新库存数量?
【发布时间】:2016-11-06 17:00:45
【问题描述】:

我正在开发一个电子商务应用程序,当用户将产品添加到购物车时,我不知道如何更新产品库存数量。 因为我是一个新手,所以我对这个应用程序的大部分内容都遵循了教程。但是本教程并没有介绍当用户将产品添加到购物车时如何更新产品库存数量。

到目前为止,我已经将此方法添加到 cart.rbmodel

 def upd_quantity
  if cart.purchased_at
   product.decrement!(quantity: params[:stock_quantity])
  end
 end

但我真的被困住了,不知道自己在做什么 如果有人可以看看这个并建议我如何在应用程序中实现这个功能,那就太好了。

这里是github repo的链接https://github.com/DadiHall/brainstore

这是我目前拥有的。

cart_item.rb型号

class CartItem
attr_reader :product_id, :quantity

  def initialize product_id, quantity = 1
    @product_id = product_id
    @quantity = quantity
  end

  def increment
    @quantity = @quantity + 1
  end

  def product
    Product.find product_id
  end

  def total_price
    product.price * quantity
  end

  def upd_quantity
   if cart.purchased_at
   product.decrement!(quantity: params[:stock_quantity])
  end
 end

end

cart.rbmodel

class Cart
    attr_reader :items

    def self.build_from_hash hash
        items = if hash ["cart"] then 
            hash["cart"] ["items"].map do |item_data|
        CartItem.new item_data["product_id"], item_data["quantity"]
        end

    else
        []
    end

        new items
    end


  def initialize items = []
    @items = items
  end

  def add_item product_id
    item = @items.find { |item| item.product_id == product_id }
    if item
      item.increment
    else
      @items << CartItem.new(product_id)
    end
  end

  def empty?
    @items.empty?
  end

  def count
    @items.length
  end

  def serialize 
    items = @items.map do |item| 
        {
            "product_id" => item.product_id, 
            "quantity" => item.quantity
        }
    end

    {

            "items" => items
    }


  end

  def total_price
    @items.inject(0) { |sum, item| sum + item.total_price }
  end
end

product.rb型号

    class Product < ActiveRecord::Base

        mount_uploader :image, ImageUploader

        validates_presence_of :name, :price, :stock_quantity
        validates_numericality_of :price, :stock_quantity

        belongs_to :designer
        belongs_to :category
        belongs_to :page

        def self.search(query)

         where("name LIKE ? OR description LIKE ?", "%#{query}%", "%#{query}%") 
        end
    end


`cart_controller.rb`

class CartsController < ApplicationController
    before_filter :initialize_cart

    def add
        @cart.add_item params[:id]
        session["cart"] = @cart.serialize
        product = Product.find params[:id]
        redirect_to :back, notice: "Added #{product.name} to cart."
    end

    def show

    end

    def checkout
        @order_form = OrderForm.new user: User.new
        @client_token = Braintree::ClientToken.generate
    end

    def remove
  cart = session['cart']
  item = cart['items'].find { |item| item['product_id'] == params[:id] }
  if item
    cart['items'].delete item
  end
   redirect_to cart_path
  end


end

【问题讨论】:

    标签: ruby-on-rails ruby e-commerce shopping-cart


    【解决方案1】:

    是否添加此行: product.update_columns(stock_quantity: product.stock_quantity - 1)

    在 CartsController 中添加操作可以解决问题吗?

    def add
        @cart.add_item params[:id]
        session["cart"] = @cart.serialize
        product = Product.find params[:id]
    
        product.update_columns(stock_quantity: product.quantity - 1)
    
        redirect_to :back, notice: "Added #{product.name} to cart."
    end
    

    试试这个从购物车中删除产品:

        def remove
            cart = session['cart']
            item = cart['items'].find { |item| item['product_id'] == params[:id] }
    
            product = Product.find(item['product_id'])
            product.update_columns(stock_quantity: product.stock_quantity + 1)
    
            if item
                cart['items'].delete item
            end
          redirect_to cart_path
        end
    

    请注意,这仅在您一次添加和删除 1 个项目/产品时才有效。我建议在删除操作中将“项目”重命名为“产品”以保持一致性。

    【讨论】:

    • 噢噢噢!!!非常感谢它有效,但在某种程度上。如果我将产品添加到购物车,库存数量会下降,但如果我从购物车中删除产品,库存数量不会再次上升
    • 这是一个非常好的建议,但它给出了 NoMethodError in CartsController#remove 错误。在这行 item = item.update_columns(stock_quantity: item.stock_quantity + 1) 中为 {"product_id"=>"14", "quantity"=>1}:Hash 说 ` undefined method 'stock_quantity'
    • 在抛出错误的行之前放置一个 byebug 语句并打印出 item 对象。让我看看它是什么样子的
    • 有道理!酷,没问题
    • 小心用 ruby​​ 做数学运算。 product.update_columns(stock_quantity: product.quantity - 1) 可能导致“竞态条件” 基本上是两个相同的产品几乎同时购买会导致错误的库存数量。而是使用 SQL 数学。 sql = "UPDATE products SET stock_quantity = (stock_quantity - #{num}) WHERE id = #{product.id}"。此外,最好有一个库存模型,这样产品模型就不会有潜在的锁定问题
    猜你喜欢
    • 2019-04-03
    • 2013-09-24
    • 1970-01-01
    • 2019-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 2020-08-30
    相关资源
    最近更新 更多