简体   繁体   English

has_and_belongs_to_many关联已更改时的Rails模型回调

[英]Rails model callback when has_and_belongs_to_many association has changed

I'm trying to fire an after_save callback on my Job model only when it has a Surveyor added or changed on it (given that one is also present too). 我试图仅在Job模型上添加或更改了Surveyor时在我的Job模型上触发after_save回调(假设还存在一个Surveyor )。

# app/models/job.rb 
has_and_belongs_to_many :surveyors
after_save :send_mail, if: ->(r) { r.surveyor_ids_changed? and r.surveyor_ids.present? }

# app/models/surveyor.rb
has_and_belongs_to_many :jobs

# permitted parameters on job
:job_name, :job_address, surveyor_ids: []

How might I change the model callback to get the send_mail method firing properly? 我如何更改模型回调以正确触发send_mail方法?

#changed? will always be false after saving the model, but you can use #previous_changes to do the thing 保存模型后,它将始终为false,但是您可以使用#previous_changes来执行此操作

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

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