Deviseのconfirmableの設定

2016/02/07 | Ruby on Rails

Railsの会員登録を可能にする「gem “devise”」の確認メールを送信する方法です。

送信元のメールアドレスの設定

[code lang=”rails” title=”config/initializers/devise.rb”]
config.mailer_sender = "youremail@yourdomeincom"
[/code]

:confirmableを追加

[code lang=”rails” title=”app/models/user.rb”]
class User < ActiveRecord::Base
devise :confirmable
end
[/code]

migrationでコメントアウト

[code lang=”rails” title=”db/migrate/xxxxxxxxx_devise_create_users.rb”]
## Confirmable
t.string :confirmation_token
t.datetime :confirmed_at
t.datetime :confirmation_sent_at
t.string :unconfirmed_email # Only if using reconfirmable
[/code]

config/environments/development.rbの設定

[code lang=”rails” title=”config/environments/development.rb”]
config.action_mailer.default_url_options = { host: ‘localhost’, port: 3000 }
[/code]
を追加。host以下のアドレスにconfirmのリンクが作成されます。
[code lang=”rails” title=”config/environments/development.rb”]
config.action_mailer.smtp_settings = {
address: "smtp.gmail.com",
port: 587,
domain: Rails.application.secrets.domain_name,
authentication: "plain",
enable_starttls_auto: true,
user_name: Rails.application.secrets.email_provider_username,
password: Rails.application.secrets.email_provider_password
}
[/code]
Defaultでは上記のようになっていますが、それぞれ設定してもメールが飛ばなかったので、以下の設定に変えてみました。gmailの場合で設定しています。
[code lang=”rails” title=”config/environments/development.rb”]
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:address =&gt; "smtp.gmail.com", # smtpサーバーのホスト名
:port =&gt; 587,
:authentication =&gt; :plain,
:user_name =&gt; "youremail@gmail.com",
:password =&gt; "password"
}
[/code]
ただし、gmailではこのままでは使えませんので、「安全性の低いアプリ」の設定を「オンにする」必要があります。
production環境やtest環境など必要な環境に記入してください。