5

我正在使用Rails 3.1.0,我想知道是否有可能处理after_saveafter_destroy回调“平等”。也就是说,我需要为after_saveafter_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_saveafter_destroy“平等”?

+1

呼叫来自相同的方法? – 2012-01-15 18:16:21

+0

@Dave Newton - 方法在字面上是相同的。 – Backo 2012-01-15 19:08:25

+0

我明白这一点 - 这就是为什么我说从两个方面调用相同的方法,不管你是在你的文章中使用表单,还是从方法参考中使用,就像在答案中一样。 – 2012-01-15 19:17:20

回答

20

代替块给after_saveafter_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 
+2

类用'class'关键字定义,而不是'def'关键字。 – Gazler 2012-01-15 18:18:41

+0

@Gazler:well spotted :) – Vapire 2012-01-15 18:23:39

5
class Foo < ActiveRecord::Base 
    after_save :my_callback 
    after_destroy :my_callback 

    private 
    def my_callback 
    #Do stuff 
    end 
end 
+0

根据用例的不同,'protected'可能比'private'更受欢迎 – ksol 2012-01-15 18:21:05

5

执行相同的回调储蓄和破坏之后,就可以使用after_commit

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

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

+0

据我的经验,这只有在事件块中包含触发事件的操作时才起作用,至少在Rails> = 3.2。否则将不会被调用。 – 2015-02-17 18:14:09

+0

这是不一样的。在'after_save'事务还没有被提交,'after_commit'事务已经被提交。 – yivo 2017-05-08 12:42:28

+0

'* _commit'仅在事务块中触发。当你“保存”时它不会触发。 – fantasticfears 2017-08-21 15:42:44

相关问题