我的股票模型具有quantity
和variant_id
属性。
我每周添加一次新库存,以用于类似这样的变体:
stock_1 = id: 1, variant_id: 1, quantity: 1, created_at: Tue, 19 Feb 2019 15:19:00 UTC +00:00
stock_2 = id: 2, variant_id: 1, quantity: 3, created_at: Tue, 26 Feb 2019 15:19:20 UTC +00:00
stock_3 = id: 3, variant_id: 1, quantity: 10, created_at: Tue, 05 Mar 2019 15:19:39 UTC +00:00
我出售商品时,要从数量大于0的第一批库存中删除它。
我尝试了这种方法,几乎可以完成工作。
问题是,如果我订购3个相同变体的文章: 从数量_1中删除3数量 因此库存将为负...
您会建议我从股票_2中删除其余的...
有没有一种方法可以改善这个想法?
@stock_1st = Stock.where(variant_id:1).where('quantity > 0').first
if @stock_1st.quantity == 0
@stock_2nd = Stock.where(variant_id: item.variant_id).where('quantity > 0').first
@stock_2nd.quantity -= item.quantity.to_i
@stock_2nd.save
else
@stock_1st.quantity -= item.quantity.to_i
@stock_1st.save
end
感谢Aleksei Matiushkin的宝贵帮助,但我仍然遇到麻烦
此处的方法:
def remove_from_stock
self.items.each do |item|
Stock.where(variant_id: item.variant_id).where('quantity > 0').order(:created_at).reduce(item.quantity.to_i) do |quantity, stock|
if leftover = item.quantity.to_i - stock.quantity <= 0
stock.update_attributes! quantity: stock.quantity - item.quantity.to_i
break
else
stock.update_attributes! quantity: 0
leftover
end
end
end
end
进行了更多测试,我确实遇到了问题:根据我的示例(上面也是)。
variant_id: 1
我的初始存货
stock_1 = id: 1, variant_id: 1, quantity: 1, created_at: Tue, 19 Feb 2019 15:19:00 UTC +00:00
stock_2 = id: 2, variant_id: 1, quantity: 3, created_at: Tue, 26 Feb 2019 15:19:20 UTC +00:00
stock_3 = id: 3, variant_id: 1, quantity: 10, created_at: Tue, 05 Mar 2019 15:19:39 UTC +00:00
如果我在此variant_id: 1
中订购了5篇文章
我的剩余库存在每个地方都是0 ...
stock_1 = 0 #1/1 article is removed from this stock
stock_2 = 0 #3/3 articles are removed from this stock
stock_3 = 0 #Only 1/10 should be removed, but stock.update_attributes! set to quantity: 0
请问该如何解决?
答案 0 :(得分:3)
您应该检索整个库存集并Enumerable#reduce
,除非分配了全部数量:
Stock.
where(variant_id: item.variant_id).
where('quantity > 0').
order(:created_at).
reduce(item.quantity.to_i) do |quantity, stock|
if (leftover = quantity - stock.quantity) <= 0
stock.update_attributes! quantity: stock.quantity - quantity
break
else
stock.update_attributes! quantity: 0
leftover
end
end