After_destroy不起作用

时间:2017-11-24 02:22:15

标签: ruby-on-rails callback

我有2个模型:Post和AuditLog,它们彼此没有关联,我想在删除Post后触发对AudiLog模型的操作。在保存帖子并且getattr(Character, attribute_name, "No skill this level") 工作正常但after_save没有。{/ p>}之后,我还在PostLog模型中发生其他回调,这些回调发生在AuditLog模型上。

after_destroy

所以在我删除帖子之后,我应该看到“再见”但是当我做

class Post < ApplicationRecord
  after_save    :confirm_audit_log, if: :submitted?
  after_destroy :say_goodbye

  private

  def confirm_audit_log
    audit_log = AuditLog.where(user_id: self.user_id, 
                start_date: (self.date - 7.days..self.date)).last
    audit_log.confirmed! if audit_log
  end

  def say_goodbye
    "Goodbye!"
  end
end

从数据库中删除post实例,但不调用回调。你能解释一下为什么吗?

更新: 我在after_destroy中改变了这个方法:

Post.last.destroy

并且它从未被调用过。我已经尝试将调试器放在uncofirm_audit_log方法中,它甚至没有到达那里。

1 个答案:

答案 0 :(得分:1)

after_destroy更改为before_destroy。我认为你会在self中得到零,因为对象被破坏了。

请尝试以下代码:

class Post < ApplicationRecord
  after_save    :confirm_audit_log, if: :submitted?
  before_destroy :unconfirm_audit_log

  private

  def confirm_audit_log
    audit_log = AuditLog.where(user_id: self.user_id, 
                start_date: (self.date - 7.days..self.date)).last
    audit_log.confirmed! if audit_log
  end

  def unconfirm_audit_log
    audit_log = AuditLog.where(user_id: self.user_id, 
              start_date: (self.date - 7.days..self.date)).last
    audit_log.pending!
  end
end