简体   繁体   English

Rails:为什么调用parent的before_save?

[英]Rails: Why before_save on parent is called?

Job has many invoices: Job有很多发票:

class Job < ActiveRecord::Base
  has_many :invoices, :autosave => true
  before_save :set_outstanding_payments
end

class Invoice < ActiveRecord::Base
  belongs_to :job
end

When invoice is updated ( @invoice.update(...) ), job's set_outstanding_payments is called. 更新发票( @invoice.update(...) )时,将调用作业的set_outstanding_payments

Why? 为什么?

I'm really astonished with this behavior since, as documentations said, autosaving is only triggered when the parent is saved. 我对这种行为感到非常惊讶,因为正如文件所述,只有父母被保存时才会触发自动保护。

The cause could be because having the :autosave => true declaration in your Job association with Invoice causes the child update to call save on the parent. 原因可能是因为在与Invoice的Job关联中使用:autosave => true声明会导致子更新在父级上调用save

When the save is called on the parent, all save hooks are called. 在父项上调用save时,将调用所有保存挂钩。 Even though, make sure you don't have any before or after update hooks in the Invoice model which messes with the parent. 尽管如此,请确保您在Invoice模型中没有任何更新挂钩之前之后与父母混淆。

For more information about the Autosave Association feature, please refer to this link: 有关自动保存关联功能的更多信息,请参阅此链接:

http://api.rubyonrails.org/classes/ActiveRecord/AutosaveAssociation.html http://api.rubyonrails.org/classes/ActiveRecord/AutosaveAssociation.html

I hope it helps somehow. 我希望它有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM