ぞえの技術めも

Ruby on Rails勉強中

【123日目】【1日20分のRailsチュートリアル】【第10章】UserMailerを生成してテンプレートをカスタマイズする

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

今日は「10.1.2 AccountActivationsメイラーメソッド」から。

10.1.2 AccountActivationsメイラーメソッド

メイラーの構成はコントローラのアクションとよく似ており、メールのテンプレートをビューと同じ要領で定義できます。
この節ではメイラーとビューを定義して、有効化トークンとメールアドレス (=有効にするアカウントのアドレス) を含むリンクをその中で使用します。

「メイラー」がそもそもよく分からないんだけど、アプリケーションでメール送るためのクラスみたいな感じかな…??

(参考)Action Mailer の基礎

メイラーは、モデルやコントローラと同様にrails generateで生成できます。

下記コマンドで「UserMailer」を生成。

$ rails generate mailer UserMailer account_activation password_reset

生成したメイラーごとに、ビューテンプレートが2つずつ生成されます。1つはテキストメール用のテンプレート、1つはHTMLメール用テンプレートです。

下記テンプレートが生成されたことを確認。

app/views/user_mailer/account_activation.text.erb

UserMailer#account_activation

<%= @greeting %>, find me in app/views/user_mailer/account_activation.text.erb

app/views/user_mailer/account_activation.html.erb

<h1>UserMailer#account_activation</h1>

<p>
  <%= @greeting %>, find me in app/views/user_mailer/account_activation.html.erb
</p>

リスト10.8には、デフォルトのfromアドレス (アプリケーション全体で共通) があります。
リスト10.9の各メソッドには宛先メールアドレスもあります。リスト10.8ではメールのフォーマットに対応するメイラーレイアウトも使用されています。

デフォルトのfromアドレスは"from@example.com"になってる。

app/mailers/application_mailer.rb

class ApplicationMailer < ActionMailer::Base
  default from: "from@example.com"
  layout 'mailer'
end

宛先メールアドレスは"to@example.org"になってるけどここは相手によって変えるとこかな…?

app/mailers/user_mailer.rb

class UserMailer < ApplicationMailer

  # Subject can be set in your I18n file at config/locales/en.yml
  # with the following lookup:
  #
  #   en.user_mailer.account_activation.subject
  #
  def account_activation
    @greeting = "Hi"

    mail to: "to@example.org"
  end

  # Subject can be set in your I18n file at config/locales/en.yml
  # with the following lookup:
  #
  #   en.user_mailer.password_reset.subject
  #
  def password_reset
    @greeting = "Hi"

    mail to: "to@example.org"
  end
end

最初に、生成されたテンプレートをカスタマイズして、実際に有効化メールで使えるようにします (リスト10.10)。

デフォルトのfromアドレスを"noreply@example.com"に変更。

app/mailers/application_mailer.rb

  default from: "noreply@example.com"

次に、ユーザーを含むインスタンス変数を作成してビューで使えるようにし、user.emailにメール送信します (リスト10.11)。

account_activationメソッドを引数ありに変更して、user.emailにメール送信するように変更。ついでにメールの件名も設定。

app/mailers/user_mailer.rb

  def account_activation(user)
    @user = user
    mail to: user.email, subject: "Account activation"
  end

途中だけど今日はここまで。

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

次は「10.1.2 AccountActivationsメイラーメソッド」のメールにアカウント有効化リンクを追加するところから。