私が実装した解決策は、デフォルトの Devise Invitable メーラーを無効にして、代わりに独自のものを使用することでした。この解決策は、Devise Invitable wiki のガイド「ユーザーがカスタム招待メッセージを作成できるようにする」にあるものと似ています。
以下の変更を行いました。
設定をカスタム メーラーに変更します。
# config/initializers/devise
config.mailer = 'CustomDeviseMailer'
カスタム メーラーで新しい Devise メール テンプレート パスを指定します (そして、Devise メール テンプレートをこのフォルダーに移動します)。
# app/mailers/customer_devise_mailer.rb
def headers_for(action, opts)
super.merge!({template_path: '/mailers/devise'}) # this moves the Devise template path from /views/devise/mailer to /views/mailer/devise
end
コマンド を使用して、上書きされた Devise Invitable 電子メールを処理するメーラーを生成しrails generate mailer InvitableMailer
ます。
Devise Invitable コントローラーの作成アクションをオーバーライドします。必要なコードは次のようになります。私のアプリケーション用にカスタマイズされているため、respond_to ブロックを省略しました。
# controllers/invitations_controller.rb
class InvitationsController < Devise::InvitationsController
# POST /resource/invitation
def create
@invited_user = User.invite!(invite_params, current_inviter) do |u|
# Skip sending the default Devise Invitable e-mail
u.skip_invitation = true
end
# Set the value for :invitation_sent_at because we skip calling the Devise Invitable method deliver_invitation which normally sets this value
@invited_user.update_attribute :invitation_sent_at, Time.now.utc unless @invited_user.invitation_sent_at
# Use our own mailer to send the invitation e-mail
InvitableMailer.invite_email(@invited_user, current_user).deliver
respond_to do |format|
# your own logic here. See the default code in the Devise Invitable controller.
end
end
end
Invitations Controller は、デフォルトのメーラーではなく、生成されたメーラーを呼び出すようになりました。メーラーにメソッドを追加して、電子メールを送信します。
# app/mailers/invitable_mailer.rb
class InvitableMailer < ActionMailer::Base
default from: "blah@blah.com"
def invite_email(invited_user, current_invitor)
@invited_user = invited_user
@current_invitor = current_invitor
# NOTE: In newever versions of Devise the token variable is :raw_invitation_token instead of :invitation_token
# I am using Devise 3.0.1
@token = @invited_user.invitation_token
@invitation_link = accept_user_invitation_url(:invitation_token => @token)
mail(to: @invited_user.email,
from: "blah@blah.com",
subject: "Invitation to SERVICE",
template_path: "/mailers/devise")
end
end
カスタム招待メールのテンプレートはapp/views/mailers/devise/invite_email.html.erb
. その電子メールで、次のコードを含む招待トークンを含む招待を受け入れる URL にリンクします。<%= link_to 'Accept invitation', @invitation_link %>
また、Invitations Controller からattr_accessible :invitation_sent_at
更新できるように、User モデルに追加しました。:invitation_sent_at attribute
これが役立つことを願っています。