我正在尝试使用railscasts第124集中的结构创建测试版邀请,并针对rails 3.2.8进行了更新。
目前,邀请电子邮件已发送,但不包含供用户注册的网址(包括邀请令牌),因为我在ActionMailer(@invitation_link)中创建的实例变量在视图中为零。在ActionMailer控制器中检查@invitation_link表明它指向了正确的URL,但在视图中它是nil。
我还检查了以下问题,但没有一个解决方案对我有用:
How do you use an instance variable with mailer in Ruby on Rails?
https://stackoverflow.com/questions/5831038/unable-to-access-instance-variable-in-mailer-view
Actionmailer instance variable problem Ruby on Rails
ActionMailer pass local variables to the erb template
以下相关代码段:
invitations_controller.rb
class InvitationsController < ApplicationController
def new
@invitation = Invitation.new
end
def create
@invitation = Invitation.new(params[:invitation])
@invitation.sender = current_user
if @invitation.save
if signed_in?
InvitationMailer.invitation(@invitation).deliver
flash[:notice] = "Thank you, invitation sent."
redirect_to current_user
else
flash[:notice] = "Thank you, we will notify when we are ready."
redirect_to root_url
end
else
render :action => 'new'
end
end
end
在invitation_mailer.rb文件中
class InvitationMailer < ActionMailer::Base
default from: "holler@thesite.com", content_type: "text/html"
def invitation(invitation)
mail to: invitation.recipient_email, subject: "Invitation"
@invitation_link = invited_url(invitation.token)
invitation.update_attribute(:sent_at, Time.now)
end
end
视图/ invitation_mailer / invitation.text.erb
You are invited to join the site!
<%= @invitation_link %> # INSTANCE VARIABLE THAT IS NIL IN VIEW
routes.rb(仅显示相关行)
match '/invited/:invitation_token', to: 'users#new_invitee', as: 'invited'
答案 0 :(得分:3)
试试这种方式
这是您的InvitationMailer
def invitation(invitation)
@invitation = invitation
mail(:to => @invitation.recipient_email, :subject => "Invitation")
end
现在,在InvitationsController
if signed_in?
@invitation.update_attribute(:sent_at, Time.now)
InvitationMailer.invitation(@invitation).deliver
...
else
...
end
现在,views/invitation_mailer/invitation.text.erb
You are invited to join the site!
<%= invited_url(@invitation.token) %> # INSTANCE VARIABLE THAT IS NIL IN VIEW
答案 1 :(得分:0)
试试这个......
@invitation_link = invited_url(invitation.token, :host => "localhost:3000")