Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

There is a way to handle `after_save` and `after_destroy` "equally"?

I am using Rails 3.1.0 and I would like to know if it is possible to handle after_save and after_destroy callbacks "equally". That is, I need to run same methods for both after_save and after_destroy callbacks.

At this time I must handle those callbacks separately even if those accomplish to the same thing:

after_save do |record|
  # Make a thing
end

after_destroy do |record|
  # Make the same thing as in the 'after_save' callback
end

So, there is a way to handle after_save and after_destroy "equally"?

like image 523
Backo Avatar asked Jan 15 '12 18:01

Backo


2 Answers

To execute the same callback after both saving and destroying, you can use after_commit

after_commit do |record|
  # Is called after creating, updating, and destroying.
end

http://apidock.com/rails/ActiveRecord/Transactions/ClassMethods/after_commit

like image 102
shock_one Avatar answered Nov 14 '22 17:11

shock_one


Instead of a block give after_save and after_destroy a method name of your model as a symbol.

class ModelName < AR
  after_save :same_callback_method
  after_destroy :same_callback_method

  def same_callback_method
    # do the same for both callbacks
  end
end
like image 29
Vapire Avatar answered Nov 14 '22 16:11

Vapire