LoginSignup
4
5

More than 5 years have passed since last update.

Confirmableを利用中のDevise(3.5.1)で登録完了時のwelcomeメールを送る方法

Posted at

ポイント

箇条書きをすると以下の通り

  • deviseがconfirmed_atをsaveするときにメールを送る
  • そのために、deviseのconfirmメソッドをオーバーライドする(※ハマリどころ: 後述)
  • メール送付は ActionMailer で。

前提として、DeviseはUserモデルに紐付いているものとします。

ActionMailerを送るための仕組み

設定、メーラクラス、テンプレートを作ります。

development環境はとりあえずgmailを使いました

config/environments/development.rb
SampleApplication::Application.configure do

  ・・・

  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = { 
    address:        'smtp.gmail.com',
    port:           587,
    domain:         'example.com',
    user_name:      'ユーザー名',
    password:       'パスワード',
    authentication: 'plain',
    enable_starttles_auto: true
  }
end

メーラクラスを準備します

app/mailers/user_mailer.rb
class UserMailer < ActionMailer::Base
  default from: "ユーザー名@gmail.com"

  def completion_of_registration(user)
    @user = user
    mail(:subject => "登録ありがとうございました", to: user.email)
  end
end

テンプレートを作ります

これがメール本文になります。

app/views/user_mailer/completion_of_registration.text.erb
登録ありがとうございました

confirmメソッドのオーバーライド

ググると、confirm!をオーバーライドしろっていう記事がいっぱい出てきますが、これで嵌まりました。

GitHubを見ると、deprecatedされてるってワーニングメッセージがあるので、本体からも呼ばれていないんでしょう。(面倒なので調査してません)

devise/lib/devise/models/confirmable.rb
def confirm!(args={})
  ActiveSupport::Deprecation.warn "confirm! is deprecated in favor of confirm"
  confirm(args)
end

ということで、Userモデルで、confirmメソッドをオーバーライドします。

app/models/user.rb
def confirm
  super
  if confirmed?
    UserMailer.completion_of_registration(self).deliver
  end
end
4
5
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
4
5