美好的一天...我已经为将要更新的特定列实现了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 控制台并运行"Product.update production:450"时,库存列将自动添加新值。 即它运行良好,但当我尝试从"视图/控制器"更新时,它根本不起作用。
请问有什么原因吗?
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**>
您已保存产品库存以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
产品在控制器中的价值。
您应该在回调中调用save
方法或使用回调before_update