【问题标题】:How to update a collection after parent is destroyed?父级销毁后如何更新集合?
【发布时间】:2013-03-20 16:30:51
【问题描述】:

我正在开发一个 Rails 3.2.13 应用程序,我有两个模型:

class Invoice < ActiveRecord::Base

  has_many :client_invoices, dependent: :nullify

  ...

end

class ClientInvoice < ActiveRecord::Base

  belongs_to :invoice

  ...

end

我想知道是否有办法让 ClientInvoices 知道其父 Invoice 何时被销毁并调用私有方法来更新其状态。

我尝试在 Invoice 的 after_destroy 回调中执行此操作,方法是循环集合并更改每个 ClientInvoice 的状态,但集合在那里已经是空的。

实现这一目标的最佳方法是什么?

非常感谢您!

【问题讨论】:

  • around_destroy 怎么样?
  • 感谢@apneadiving 的回复,但是在 around_destroy 中,client_invoices 集合是空的,所以我无法遍历它们……为什么会这样?
  • 销毁前获取集合,之后循环

标签: ruby-on-rails activerecord callback


【解决方案1】:

before_destroy 会起作用。

before_destroy :update_client_invoice_statue

private

def update_client_invoice_statue   
  client_invoices.each do |invoice|
    #... code to update the status of record
  end
end

注意:此 before_destroy 方法应返回 true 以继续销毁对象。

【讨论】:

  • 感谢您的回复!我会尽快试一试
  • 嗨!抱歉,我还没有机会测试它。一旦我完成了一些未完成的工作,它就在我的待办事项列表中。再次感谢!
猜你喜欢
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 2023-02-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多