LoginSignup
0
0

More than 3 years have passed since last update.

Rails Tutorial(2週目)-11-

Posted at
1 / 2

アカウントの有効化

Userモデルにactivation_digestとactivated属性を追加する

app/models/user.rb
class User < ApplicationRecord
  attr_accessor :remember_token, :activation_token
  before_save   :downcase_email
  before_create :create_activation_digest
  validates :name,  presence: true, length: { maximum: 50 }
  .
  .
  .
  private

    # メールアドレスをすべて小文字にする
    def downcase_email
      self.email = email.downcase
    end

    # 有効化トークンとダイジェストを作成および代入する
    def create_activation_digest
      self.activation_token  = User.new_token
      self.activation_digest = User.digest(activation_token)
    end
end

before_createコールバックによりオブジェクトが作成される前に有効化トークンの作成、トークンの暗号化を行っている。

メイラーの作成

メイラーはコントローラーとよく似た構成
rails generate mailer 名前(キャメルケース) メソッド名で生成できる

コントローラーの作成と同時にビューのテンプレートがテキストメール用のものとHTMLメール用のものの2つが作られる。

app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base
  default from: "noreply@example.com"
  layout 'mailer'
end

fromのところで送信元アドレスの指定。

app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer

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

  def password_reset
    @greeting = "Hi"

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

mail:toで送信先のアドレスを指定。subjectはメールの件名

アカウントの有効化はユーザーのメールアドレスから検索して有効化トークン認証するので、URLにはメールアドレスと有効化トークンの両方を含ませる必要がある。

edit_account_activation_url(user)http://www.example.com/users/1/editというURLが生成されるので、同じ要領でedit_account_activation_url(@user.activation_token, email: @user.email)というURLを指定することでaccount_activations/q5lt38hQDc_959PVoo6b7A/edit?email=foo%40example.comといったURLが生成される。

メール送信後のアカウント有効化

URLからparams[:id]とparams[:email]で有効化トークンとメールアドレスのそれぞれを取得することができる

seldメソッド

このメソッドは、渡されたオブジェクトに「メッセージを送る」ことによって、呼び出すメソッドを動的に決めることができます。

sendに引数として渡した文字列やシンボルを、sendメソッドのレシーバのオブジェクトに対してメソッドとして実行する

0
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
0
0