ぞえの技術めも

Ruby on Rails勉強中

【134日目】【1日20分のRailsチュートリアル】【第10章】パスワードリセットのメールプレビュー機能を実装する

Ruby on Railsチュートリアル(第3版)

今日は「10.2.3 PasswordResetsメイラーメソッド」から。

10.2.3 PasswordResetsメイラーメソッド

最初にユーザーメイラーにpassword_resetメソッドを作成し (リスト10.43)、続いてテキストメールのビューテンプレート (リスト10.44) と HTMLメールのビューテンプレート (リスト10.45) をそれぞれ定義します。

アカウント有効化のときと同じようにメソッドとビュー追加。

app/mailers/user_mailer.rb

  def password_reset(user)
    @user = user
    mail to: user.email, subject: "Password reset"
  end

app/views/user_mailer/password_reset.text.erb

To reset your password click the link below:

<%= edit_password_reset_url(@user.reset_token, email: @user.email) %>

This link will expire in two hours. 

If you did not request your password to be reset, please ignore this email and
your password will stay as it is.

app/views/user_mailer/password_reset.html.erb

<h1>Password reset</h1>

<p>To reset your password click the link below:</p>

<%= link_to "Reset password", edit_password_reset_url(@user.reset_token,
                                                      email: @user.email) %>

<p>This link will expire in two hours.</p>

<p>
If you did not request your password to be reset, please ignore this email and
your password will stay as it is.
</p>

アカウント有効化メールの場合 (10.1.2) と同様、Railsのメールプレビュー機能でパスワード再設定のメールをプレビューしましょう。

メールプレビュー機能を実装する。

test/mailers/previews/user_mailer_preview.rb

  # Preview this email at http://localhost:3000/rails/mailers/user_mailer/password_reset
  def password_reset
    user = User.first
    user.reset_token = User.new_token
    UserMailer.password_reset(user)
  end

ここまで実装できたら動作確認。

サーバーを起動して

$ rails server -b $IP -p $PORT

<ローカルアドレス>/rails/mailers/user_mailer/password_resetにアクセス。

f:id:kt_zoe:20170417123833p:plain

f:id:kt_zoe:20170417123845p:plain

パスワードリセットのメールプレビューが確認できました。

今日の学習時間は【17分】

次は「10.2.3 PasswordResetsメイラーメソッド」のテストを書くところから。