【问题标题】:before_destroy callback on rails轨道上的 before_destroy 回调
【发布时间】:2014-11-17 10:39:16
【问题描述】:

我想在我的 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.

就这样。

请帮帮我。

【问题讨论】:

  • 在删除记录之前你想做什么?
  • 我不知道你到底是什么问题?
  • 我更新了问题以获得进一步的解释。
  • “用户一”是否应该具有当前用户的 id?

标签: ruby-on-rails callback


【解决方案1】:

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

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

所以就这么简单,除非你换了别的东西?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-15
    • 2022-08-14
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多