Reputation: 217
I have some trouble to use after_destroy in model
Here is this one:
class Transaction < ActiveRecord::Base
belongs_to :user
delegate :first_name, :last_name, :email, to: :user, prefix: true
belongs_to :project
delegate :name, :thanking_msg, to: :project, prefix: true
validates_presence_of :project_id
after_save :update_collected_amount_in_project
after_update :update_collected_amount_if_disclaimer
after_destroy :update_collected_amount_after_destroy
def currency_symbol
currency = Rails.application.config.supported_currencies.fetch(self.currency)
currency[:symbol]
end
private
def update_collected_amount
new_collected_amount = project.transactions.where(success: true, transaction_type: 'invest').sum(:amount)
project.update_attributes(collected_amount: (new_collected_amount / 100).to_f) # Stored in € not cents inside projects table
end
def update_collected_amount_in_project
update_collected_amount if transaction_type == 'invest' && success == true
end
def update_collected_amount_if_disclaimer
update_collected_amount if transaction_type == 'invest' && self.changes.keys.include?('success') && self.changes.fetch('success', []).fetch(1) == false
end
def update_collected_amount_after_destroy
update_collected_amount
end
end
When I use something like:
Transaction.last.delete
It never go inside my after_destroy, I tried to include some outputs but nothing. I don't know if I'm wrong on how I use this after_destroy
, I also tried before_destroy
and I have the same problem. after_save
and after_update
work perfectly.
Upvotes: 6
Views: 2247
Reputation: 1112
I think you can use rails-observer gem, that can help you in adding after_destroy callback
Upvotes: 0
Reputation: 24070
The after_destroy
callbacks aren't called on delete
. They are only called if you call destroy
, like so:
Transaction.last.destroy
That's actually the only difference between the two methods. Delete
bypasses the callbacks.
Delete also won't execute any :dependent
association options.
The reason for this is that it never instantiates any of the active record objects that you are deleting, it simply executes an SQL delete statement against the database.
Upvotes: 14