【发布时间】:2012-09-04 18:40:45
【问题描述】:
所以我有两个模型:Product和Sale。它们通过 has_many :trough 关联关联,并且都具有相同的属性和属性名称(sale 更难):
代码片段:
# Product Model
class Product < ActiveRecord::Base
attr_accessible :qty, :color, :name, :price, :size, :type, :code
has_many :orders
has_many :sales, :through => :orders
end
# Sale Model
class Sale < ActiveRecord::Base
attr_accessible :qty, :color, :name, :salesman_name, :price, :size, :type, :code
has_many :orders
has_many :productos, :through => :orders
end
我想要做的是每次创建带有名称的新销售时,减少特定记录(产品)的 Products>Quantity 属性。 .. 减法必须等于新销售创建中设置的与创建的产品相关的“数量”的值...
该应用程序是一个非常简单的库存系统,我在其中跟踪 库存商品 和销售情况,让我们举一个实际的例子:假设我在 Products中有一个名为“Socks”的产品> 数据库,我将“30”作为该产品的 qty 属性,然后有人销售 两只袜子(在应用程序中创建一个包含 2 只袜子的新销售):情况下,我希望 Products 数据库中“Socks”的值自动更新为 28。
我一直在阅读,我认为这可以通过带有 ActiveRecord 事务的销售模型中的 after_create 回调来完成,但我不确定如何实现这一点,有人可以帮我吗? 顺便说一句,我正在考虑在这里使用类似的东西:
after_create :decrement_stock
def decrement_stock
Sale.transaction do
Product.transaction do
@substraction = product.sale(params[:qty])
product.update_attributes!(:qty => @qty - @substraction)
end
end
end
但我很确定它不会起作用,请指出正确的方向......我一直在努力解决这个问题。
谢谢,祝你有美好的一天。
【问题讨论】:
标签: ruby-on-rails-3 activerecord transactions callback