首页 > 解决方案 > 如何根据数量复制记录

问题描述

我正在实施一个优惠券/优惠券系统,用户可以为给定的产品购买一对多的优惠券。例如,用户可以在零售商 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 来存储条带令牌 - 希望对您有所帮助。

标签: ruby-on-railsrubypostgresqlruby-on-rails-5

解决方案


我不会使用同一张表来订购商品和优惠券/代金券。如果我在你的位置,我会删除 order_item 表中的 claim_on 字段并创建一个子表

VoucherCoupon
    id
    order_item
    claimed_on

推荐阅读