Is there a way to handle after_save and after_destroy equals?

I am using Rails 3.1.0, and I would like to know if the after_save and after_destroy callbacks can be handled β€œthe same”. That is, I need to run the same methods for both after_save and after_destroy callbacks.

At this time, I have to handle these callbacks separately, even if they do 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, is there a way to handle after_save and after_destroy equals?

+5
source share
3 answers

Instead of a block, enter after_save and after_destroy name of the method 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 
+20
source
 class Foo < ActiveRecord::Base after_save :my_callback after_destroy :my_callback private def my_callback #Do stuff end end 
+6
source

To perform the same callback after 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

+5
source

Source: https://habr.com/ru/post/906031/


All Articles