gpt4 book ai didi

mysql - after_update 回调不会更新属性

转载 作者:太空宇宙 更新时间:2023-11-03 17:46:17 25 4
gpt4 key购买 nike

美好的一天...我已经为将要更新的特定列实现了 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 produced:450”时,stock 列将自动添加新值。即它工作得很好但是当我尝试从“ View / Controller ”更新时它根本不起作用。

请问有什么原因吗?

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_stock 回调中,您只设置产品库存的值。 self.stock = self.stock + self.produced 只设置产品库存的值。

要更新股票值(value),您必须在回调中保存为:

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 回调设置股票值(value)。

  class Product < ActiveRecord::Base
before_update :update_stock, :if => :produced_changed?

private

def update_stock
self.stock = self.stock + self.produced
end
end

并且在 Controller 中保存产品的值(value)。

关于mysql - after_update 回调不会更新属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36768490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com