我正在使用Rails 3.1.0,我想知道是否可以“同等”地处理after_save
和after_destroy
回调。也就是说,我需要为after_save
和after_destroy
回调运行相同的方法。
此时我必须单独处理这些回调,即使这些回调达到同样的目的:
after_save do |record|
# Make a thing
end
after_destroy do |record|
# Make the same thing as in the 'after_save' callback
end
那么,有一种方法可以同等地处理after_save
和after_destroy
吗?
答案 0 :(得分:29)
而不是阻止将after_save
和after_destroy
模型的方法名称作为符号。
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
答案 1 :(得分:7)
class Foo < ActiveRecord::Base
after_save :my_callback
after_destroy :my_callback
private
def my_callback
#Do stuff
end
end
答案 2 :(得分:6)
要在保存和销毁后执行相同的回调,您可以使用after_commit
after_commit do |record|
# Is called after creating, updating, and destroying.
end
http://apidock.com/rails/ActiveRecord/Transactions/ClassMethods/after_commit