首页 > 解决方案 > 如何从嵌套表单值更新关联记录

问题描述

我在尝试运行的回调方法上遇到困难。我有一张发票,其中包含采购条目的嵌套表格(一个表格中的多个发票条目)。每个采购条目都有单独的产品、数量和价格。

我在购买条目上有一个回调函数来更新关联产品的数量 - 例如:

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 方法使用所有购买条目中的总数量更新数据库,而不仅仅是创建的新购买条目。如何将方法限制为仅已创建的条目?

标签: ruby-on-railsruby

解决方案


如何将方法限制为仅已创建的条目?

=>before_save每次对象为 时都会被调用saved。所以对于新的和现有的对象。(创建和更新操作)

=>before_create仅在创建之前。因此仅适用于新对象(创建操作)

=> Rails 5 具有after_create_commit after_update_commitand 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

推荐阅读