2

我正在尝试使用 railscasts 第 124 集的结构创建 beta 邀请,为 rails 3.2.8 更新。

目前,邀请电子邮件已发送,但不包含供用户注册的 url(包括邀请令牌),因为我在 ActionMailer (@invitation_link) 中创建的实例变量在视图中为零。在 ActionMailer 控制器中检查 @invitation_link 表明它指向正确的 url,但在视图中它是 nil。

我还检查了以下问题,但没有一个解决方案对我有用:

如何在 Ruby on Rails 中将实例变量与邮件程序一起使用?

https://stackoverflow.com/questions/5831038/unable-to-access-instance-variable-in-mailer-view

Actionmailer 实例变量问题 Ruby on Rails

ActionMailer 将局部变量传递给 erb 模板

相关代码片段如下:

邀请控制器.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'
4

2 回答 2

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
于 2012-11-09T06:50:33.143 回答
0

试试这个...

@invitation_link = invited_url(invitation.token, :host => "localhost:3000")

于 2012-11-09T06:22:54.443 回答