美好的一天......我已经为要更新的特定列实现了after_update回调,并且在更新该列之后,回调意味着将新更新的值添加到另一列,即
class Product < ActiveRecord::Base
after_update :update_stock, :if => :produced_changed?
private
def update_stock
self.stock = self.stock + self.produced
end
end
当我运行rails console并运行“Product.update produce:450”时,stock列将自动添加新值。即它工作得很好但是当我尝试从“视图/控制器”进行更新时它根本不起作用。
请问有原因吗?
2.2.4 :004 > h
=> Product id: 1, name: "MAC Air Filter", partnumber: 33440, description: "Air filter", **stock: 3440**, created_at: "2016-04-08 11:38:58", updated_at: "2016-04-19 20:33:00", **produced: 33**
2.2.4 :006 > h.update **produced:3000**
(0.1ms) SAVEPOINT active_record_1
SQL (1.4ms) UPDATE "products" SET "produced" = ?, "updated_at" = ? WHERE "products"."id" = ? [[**"produced", 3000**], ["updated_at", "2016-04-20 13:57:59.377954"], ["id", 1]]
(0.1ms) RELEASE SAVEPOINT active_record_1
=> true
2.2.4 :007 > h
=> Product id: 1, name: "MAC Air Filter", partnumber: 33440, description: "Air filter", **stock: 6440**, created_at: "2016-04-08 11:38:58", updated_at: "2016-04-20 13:57:59", **produced: 3000**>
答案 0 :(得分:3)
您已将产品库存保存到产品的update
。在update_stock
回调中,您只需设置产品库存的值。 self.stock = self.stock + self.produced
仅设置产品库存的价值。
要更新您必须在回调中保存的股票价值:
class Product < ActiveRecord::Base
after_update :update_stock, :if => :produced_changed?
private
def update_stock
self.stock = self.stock + self.produced
self.save
end
end
但它运行无限循环并给出错误。因此,您必须使用before_update回调在更新前设置库存值。
class Product < ActiveRecord::Base
before_update :update_stock, :if => :produced_changed?
private
def update_stock
self.stock = self.stock + self.produced
end
end
save
控制器中产品的价值。
答案 1 :(得分:1)
您应该在回调中调用save
方法或使用回调before_update