【问题标题】:Updating product stock based on shopping cart quantity and updating cart items when product is changed根据购物车数量更新产品库存并在产品更改时更新购物车项目
【发布时间】:2013-09-24 03:34:22
【问题描述】:

今天只是一个(希望)快速的,如果它超级简单而且我很厚,请道歉。

我正在开发一个基本的电子商务应用程序,并且有 2 个问题:

  1. 我会在 admin 中创建一个带有一定数量库存的 :product。如果一个或多个作为 :cart_item 添加到某人的购物车中,我希望根据他们在购物车中的数量(甚至在结帐之前)自动更新 :product 的库存。因此,如果添加了产品,则更新一次,如果客户从购物车视图中更改数量,则更新一次。
  2. 如果管理员更新关联的 :product,我希望自动更新客户购物车中 :cart_item 的名称和价格。

到目前为止,这是我的模型关联:

Customer
  has_one :cart
  has_many :orders

Product
  has_many :cart_items

Cart
  belongs_to:customer
  has_many :cart_items

CartItem
  belongs_to :product
  belongs_to :cart

到目前为止,我只有脚手架,所以我当前的所有代码都是开箱即用的 Rails 3.2.14。

我只是不确定如何让 :cart_items 与 :products 交互,反之亦然。我应该添加哪些代码/额外功能才能使其正常工作?感谢您的帮助。

【问题讨论】:

  • 只是一个建议,但请记住,大多数购物车都已废弃。通常在交易完成后才会调整库存。

标签: ruby-on-rails ruby-on-rails-3 e-commerce


【解决方案1】:

假设CartItem belongs_to :product(这似乎很可能),并且有一个quantity 属性表示购物车中的数字:

1) 我相信您想要的功能可以使用CartItem 上的回调来完成。例如,

class CartItem < AR:B
  after_save :remove_from_stock
  after_destroy :return_to_stock


  def remove_from_stock
    product.stock -= self.quantity
    product.save
  end

  def return_to_stock
    product.stock += self.quantity
    product.save
  end
end

2) 当您显示CartItem 时,只需参考它的关联产品:

<% @cart_items.each do |cart_item| %>
  Item Name: <%= cart_item.product.name %>
  Item Price: <%= cart_item.product.price %>
<% end %>

这样,对关联Product 的任何更改都将反映在引用它的任何视图中。 如果您一次显示多个,请确保使用预加载以避免 N+1 查询:

@cart_items = CartItem.includes(:product).where(<whatever>)

【讨论】:

    猜你喜欢
    • 2015-07-21
    • 1970-01-01
    • 2014-09-12
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多