【问题标题】:Mongoid after save call back runs twice保存回调后的 Mongoid 运行两次
【发布时间】:2016-08-17 02:22:59
【问题描述】:
class SubJob
  field :total_qty
end

class Part

  belongs_to :sub_job
  after_save :update_inventory, if: ready_for_invoice
  after_save :update_total_qty

  def update_inventory
    # creating one more part2 
    part2 = Part.create(ready_for_invoice: false)
  end

  def update_total_qty
    # updating total qty on sub job
  end
end

当我创建 p1 = Part.create 时,它也会创建 part2 对象。但它为part2 子作业更新了两次数量。我已经检查了 part2 对象的历史跟踪器。它显示了两个历史跟踪器,但数据库上只有一个 part2 对象。任何帮助都会很棒。

【问题讨论】:

    标签: mongodb mongoid mongoid4


    【解决方案1】:

    首先,我不是百分百了解您的错误/问题是什么,但我希望了解您的代码中发生的事情会有所帮助:

    我假设 ready_for_invoice 默认为 true。

    因此,您所编码的内容是:

    创建一个新部件,将 ready_for_invoice 设置为 true

    p1 = Part.create
    

    保存后,如果 ready_for_invoice = true(确实如此)

    # run update_inventory first
    

    创建一个新部件,将 ready_for_invoice 设置为 false

    p2 = Part.create(ready_for_invoice: false)
    

    保存后 p2

    # run update_total_qty (doing whatever that does)
    

    保存后 p1

    # run update_total_qty (doing whatever that does)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-22
      • 2017-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多