ruby-on-rails - 如何根据数量复制记录
问题描述
我正在实施一个优惠券/优惠券系统,用户可以为给定的产品购买一对多的优惠券。例如,用户可以在零售商 X 购买两张优惠券以购买有折扣的软饮料。可以同时或在 2 个不同的时间点领取优惠券,即今天领取一张,明天领取下一张。
将优惠券添加到购物车时,将生成订单以及每张优惠券的关联 order_item + 数量。
结帐成功完成后,我需要复制优惠券,quantity > 1
因为我需要为每个优惠券提供一个 claim_on 时间戳以用于审计目的。
换句话说,我需要从以下位置更新 OrderItem:
id,quantity,order_id,product_id,claimed_on
1, 2, 001, 010, nil
2, 3, 001, 020, nil
在购物车中
id,quantity,order_id,product_id,claimed_on
1, 1, 001, 010, nil
2, 1, 001, 020, nil
3, 1, 001, 010, nil
4, 1, 001, 020, nil
5, 1, 001, 020, nil
一旦购买成功。
到目前为止,我已经找到了这个答案,但我很难从 activerecord 的角度来看实现。我主要担心的是当多个用户使用该平台时会生成任何类型的锁定或损坏表。
我已经考虑创建一个仅包含成功订单但似乎不是一个好习惯的第三个表。
这是我的模型:
class Order < ApplicationRecord
belongs_to :user
has_many :order_items
end
OrderItem 看起来像:
# id :bigint(8) not null, primary key
# quantity :integer default(0), not null
# created_at :datetime not null
# updated_at :datetime not null
# order_id :bigint(8)
# product_id :bigint(8)
#
# Indexes
#
# index_order_items_on_order_id (order_id)
# index_order_items_on_product_id (product_id)
#
# Foreign Keys
#
# fk_rails_... (order_id => orders.id)
# fk_rails_... (product_id => products.id)
#
class OrderItem < ApplicationRecord
belongs_to :order
belongs_to :product
validates :quantity, numericality: { greater_than_or_equal_to: 0 }
after_save :destroy_if_zero
def total
quantity * product.active_product_prices.price
end
private
def destroy_if_zero
destroy if quantity.zero?
end
end
更新:
我正在使用条带处理付款,因此 Order 模型有一个 Charge_id 来存储条带令牌 - 希望对您有所帮助。
解决方案
我不会使用同一张表来订购商品和优惠券/代金券。如果我在你的位置,我会删除 order_item 表中的 claim_on 字段并创建一个子表
VoucherCoupon
id
order_item
claimed_on
推荐阅读
- azure-language-understanding - 您可以在 LUIS 中将一个单词标记为多个实体吗
- bash - 如何在 bash 中打开文件夹中的文件?
- ruby-on-rails - 跨 Rails 版本更好地打印变量
- typo3 - Typo3 v9.5LTS 部分不渲染
- uitableview - Xamarin iOS TableView Checkmark 行也检查其他行
- c++ - 以模板类的嵌套模板类为参数的函数
- javascript - 高效渲染大量 Redux 表单字段?
- excel - Power Query:索引调整解决方案
- python - 使用 BeautifulSoup 获取特定的 a href
- vb.net - 每 30 秒自动刷新表单 vb.net