跳至内容 跳至搜索

Active Record Suppressor

ActiveRecord::Suppressor 阻止接收器在给定块期间被保存。

例如,以下是在发布新评论时创建通知的模式。(该通知可能反过来触发电子邮件、推送通知或仅出现在 UI 的某个位置)

class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
  after_create -> { Notification.create! comment: self,
    recipients: commentable.recipients }
end

这是你大部分时间想要的内容。新评论会创建一个新通知。但很可能会有特殊情况,例如复制可评论内容及其评论,在这种情况下你不需要这样做。因此,你会有类似这样的疑虑

module Copyable
  def copy_to(destination)
    Notification.suppress do
      # Copy logic that creates new comments that we do not want
      # triggering notifications.
    end
  end
end
命名空间