before_destroy在rails上回调

时间:2014-11-17 10:39:16

标签: ruby-on-rails callback

我想在我的rails应用程序中使用before_destroy回调。我想使用它,因为我在通知中使用它。但是我如何使用before_destroy?

我的代码在before_saveafter_save,但我不知道我会为before_destroy做些什么。

class Record < ActiveRecord::Base
  # Callbacks
  before_save {
    @is_new_record = self.new_record? if self.new_record?
  }

  after_save {
    action = @is_new_record ? 'created' : 'updated'
    Notification.publish_notification(self, action)
  }

  ...
  #Some stuffs here

更新


实际上,我想保存表Notification的日志,就像创建新记录一样。 像,

User One created new Record.

所以我想在销毁记录之前保存通知。就像。

User One destroy a record.

就像那样。

请帮帮我。

1 个答案:

答案 0 :(得分:4)

我更喜欢使用方法而不是匿名块。我会按如下方式处理:

class Record < ActiveRecord::Base

  before_save :remember_new_record
  after_save  :write_save_notification
  before_destroy :write_destroy_notification

  # ... the rest of your class ...

  private

    def remember_new_record
      @is_new_record = self.new_record? 
    end

    def write_save_notification 
      action = @is_new_record ? 'created' : 'updated'
      Notification.publish_notification(self, action)
    end

    def write_destroy_notification
      Notification.publish_notification(self, 'destroy')
    end
  end

所以这很简单,除非你做别的事情?