ポイント
箇条書きをすると以下の通り
- 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