只需在Rails 4上设置我的第一封邮件。一旦他们使用设计注册(创建)新帐户,我就会向新用户发送欢迎电子邮件。
我还设置了设置,如果找不到current_user,将创建一个访客用户。不幸的是,这干扰了邮件。每次创建访客帐户时,邮件程序都会向不存在的电子邮件发送电子邮件。
我无法弄清楚如何将客人从邮件中排除。
user.rb:
after_create :send_welcome_mail
def send_welcome_mail
UserMailer.welcome_email(self).deliver
end
寄件人/ user_mailer.rb:
class UserMailer < ActionMailer::Base
default from: "example@gmail.com"
def welcome_email(user)
@user = user
mail(:to => user.email, :subject => "Welcome!")
end
end
application_controller.rb(创建访客):
def current_or_guest_user
if current_user
if session[:guest_user_id] && session[:guest_user_id] != current_user.id
logging_in
guest_user(with_retry = false).try(:destroy)
session[:guest_user_id] = nil
end
current_user
else
guest_user
end
end
# find guest_user object associated with the current session,
# creating one as needed
def guest_user(with_retry = true)
# Cache the value the first time it's gotten.
@cached_guest_user ||= User.find(session[:guest_user_id] ||= create_guest_user.id)
rescue ActiveRecord::RecordNotFound # if session[:guest_user_id] invalid
session[:guest_user_id] = nil
guest_user if with_retry
end
private
# called (once) when the user logs in, insert any code your application needs
# to hand off from guest_user to current_user.
def logging_in
# For example:
# guest_comments = guest_user.comments.all
# guest_comments.each do |comment|
# comment.user_id = current_user.id
# comment.save!
# end
end
def create_guest_user
u = User.create(:name => "guest", :email => "guest_#{Time.now.to_i}#{rand(100)}@example.com")
u.save!(:validate => false)
session[:guest_user_id] = u.id
u
end
我确信这很容易,但我仍然是新手,并且对于解决此问题的最佳方式感到有些困惑。如果您需要任何其他代码,请告诉我。
答案 0 :(得分:1)
def welcome_email(user)
# The following line is unnecessary. Normally, you do
# something like this when you want to make a variable
# available to a view
#@user = user
# You can make the if more explicit by writing
# if user.id == nil, but if will return false in
# Ruby if a value doesn't exist (i.e. is nil)
if user.id
mail(:to => user.email, :subject => "Welcome!")
end
end