gpt4 book ai didi

ruby-on-rails - Rails - 电子邮件 View 中的邮件程序实例变量 Nil

转载 作者:行者123 更新时间:2023-12-04 05:24:56 27 4
gpt4 key购买 nike

我正在尝试使用 railscasts 第 124 集(针对 rails 3.2.8 更新)中的结构创建测试版邀请。

目前,邀请电子邮件已发送,但不包含供用户关注以进行注册的 url(包括邀请 token ),因为我在 ActionMailer (@invitation_link) 中创建的实例变量在 View 中为零。检查 ActionMailer Controller 中的 @invitation_link 表明它指向正确的 url,但它在 View 中为零。

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

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

相关代码片段如下:

邀请_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

route.rb(仅显示相关行)
match '/invited/:invitation_token', to:  'users#new_invitee', as: 'invited'

最佳答案

试试这个方法

这是您的 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

关于ruby-on-rails - Rails - 电子邮件 View 中的邮件程序实例变量 Nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13302414/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com