Reputation: 2198
I have 2 models: Post and AuditLog, they are not associated with each other, and I want to trigger an action on AudiLog model after a Post has been deleted. I also have other callbacks in Post model that happen on AuditLog model after a Post is saved and after_save
works fine but after_destroy
does not.
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
So after I delete a post I should see "Goodbye" but when I do
Post.last.destroy
The post instance is deleted from the database but the callback is not called. Can you please explain to me why?
UPDATE: I have changed to this metod in after_destroy:
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
and it's never called. I have tried putting debugger inside of the uncofirm_audit_log method and it does not even reach there.
Upvotes: 0
Views: 1138
Reputation: 4427
change after_destroy
to before_destroy
. I think you will get nil in self
because object is destroyed.
So try below code:
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
Upvotes: 1