ruby-on-rails - 如何从嵌套表单值更新关联记录
问题描述
我在尝试运行的回调方法上遇到困难。我有一张发票,其中包含采购条目的嵌套表格(一个表格中的多个发票条目)。每个采购条目都有单独的产品、数量和价格。
我在购买条目上有一个回调函数来更新关联产品的数量 - 例如:
class PurchaseEntry < ActiveRecord::Base
before_save :update_quantity
belongs_to :product
def update_quantity
if product.present?
product.update_quantity
end
end
然后,在我的产品模型中,我有以下
class Product < ActiveRecord::Base
has_many :purchase_entries
def update_quantity
update(quantity: purchase_entry.sum(:quantity))
end
然而,update_quantity 方法使用所有购买条目中的总数量更新数据库,而不仅仅是创建的新购买条目。如何将方法限制为仅已创建的条目?
解决方案
如何将方法限制为仅已创建的条目?
=>before_save
每次对象为 时都会被调用saved
。所以对于新的和现有的对象。(创建和更新操作)
=>before_create
仅在创建之前。因此仅适用于新对象(创建操作)
=> Rails 5 具有after_create_commit
after_update_commit
and after_destroy_commit
(after_commit
在创建、更新或销毁记录后调用。)
所以,你可以这样做: -
class PurchaseEntry < ActiveRecord::Base
after_create_commit :update_quantity
belongs_to :product
def update_quantity
if product.present?
product.update_quantity
end
end
end
推荐阅读
- python - 尝试在烧瓶中使用 POST 时出现 404
- javascript - Reactstrap 中的按钮下拉菜单无法正常工作 | 反应 JS
- sql - the max value Less than
- azure-devops - QNA maker - 知识库 - Azure DevOps 管道,如何创建任何示例?
- node.js - .findOneAndUpdate() 删除数组中的所有元素
- mongodb - MongoDB如何计算子文档总数大于3且子文档值之和大于15000的地方
- python - 如何从python中的文本文件中仅获取日期
- python - numpy polyfit 没有根据卡方给出最佳线性拟合
- apache-kafka - 如何从 Kafka 全局状态存储中删除记录?
- scala - 如何在集成测试和单元测试之间共享代码