1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ActionMailer::Previewで作成したデータをrollbackする

Posted at

概要

previewのたびにレコードを作成するのは嫌だ。
buildしたものを使うことで回避できそうだがActiveRecord_Associations_CollectionProxyに対しorderを使っている部分があるとDBを探しにいってしまい、空配列が返ってしまう。
orderではなくsort_byを使うとindexが効かなくなる
なので一旦レコードを作成してしまい、メールをrenderした後にrollbackする。

方法

config/initializers/mailer_previews.rb

module RollbackingAfterPreview
  def preview
    ActiveRecord::Base.transaction do
      super
      raise ActiveRecord::Rollback
    end
  end
end

Rails.application.config.after_initialize do
  class Rails::MailersController
    prepend RollbackingAfterPreview
  end
end

参考

ruby on rails - How to avoid ActionMailer::Preview committing data to development database? - Stack Overflow

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?