我的 Stock 模型有 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 篇相同变体的文章: 3 数量将从库存中移除_1 所以存货会是负的……
你会建议我从 stock_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
请问我该如何解决这个问题?
最佳答案
您应该检索整个库存集和 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
关于ruby-on-rails - 如果第一个对象数量 == 0,则删除下一个对象中的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55125581/