我有一个模型,它通过解析名称和电子邮件的 CSV 文件来通过电子邮件发送邀请。我有一个 before_create 创建一个 url 并将其保存为实例变量。创建记录后,它应该将结果连同 URL 的实例变量一起发送到邮件程序。当电子邮件成功发送时,似乎没有将 URL 发送到邮件程序,而是使用 URL。下面是相关的代码行。我确认正在创建邀请令牌,所以这不是问题。
注意:我使用 SmarterCSV gem 来解析 csv 并使用 delay_jobs gem 创建后台进程。
让我解释一下这个过程:
控制器(未显示)接收 CSV 并将其发送到 Invitation.import。解析文件并在创建记录之前创建邀请令牌,然后构建 URL。然后发送电子邮件。
谢谢!
控制器:invitations_controller.rb
class InvitationsController < ApplicationController before_filter :get_event #, only: [:create]
def new
@invitation = @event.invitations.new
end
def create
@invitation = @event.invitations.build(params[:invitation])
@invitation.event_id = params[:event_id]
if @invitation.save
flash[:success] = "Invitation confirmed!"
render 'static_pages/home'
else
render 'new'
end
end
def import_csv
@invitation = @event.invitations.new
end
def import
Invitation.import(params[:file], params[:event_id])
flash[:success] = "Invitations sent!"
redirect_to @event
end
private
def get_event
@event = Event.find(params[:event_id])
end
end
型号:Invitation.rb
class Invitation < ActiveRecord::Base
before_save { |user| user.email = user.email.downcase }
before_create :create_invite_token
before_create :build_url
@@url = "" #added 9/8/13
def self.import(file, id)
file_path = file.path.to_s
file_csv = SmarterCSV.process(file_path)
file_csv.each do |x|
x[:event_id] = id
Invitation.delay.create! x
UserMailer.delay.invitation_email(x, @@url)
end
end
def build_url
@@url = 'http://localhost:3000/confirmation/' + self.invite_token
end
private
def create_invite_token
self.invite_token = SecureRandom.urlsafe_base64
end
end
邮件:user_mailer.rb
def invitation_email(invitation, signup_url)
@invitation = invitation
@signup_url = signup_url
mail(:to => invitation[:email], :subject => "You're invited!")
end
邀请邮件:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
</head>
<body>
<h2>Hi <%= @invitation[:name].split.first %>,</h2>
<p>
Click here: <%= @signup_url %>
</p>
</body>
</html>