跳到內文跳到搜尋

Active Record Suppressor

ActiveRecord::Suppressor可防止接收者在給定的區塊期間儲存。

例如,以下是新留言發佈時建立通知的範例 (通知可能會觸發電子郵件、推播通知,或只是顯示在使用者介面中的某處)

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
命名空間