Just set up my first mailer on Rails 4. I have a welcome email sent to new users as soon as they sign up (create) for a new account using devise.
I also have devise set up so that if a current_user is not found, a guest user will be created. Unfortunately, this is interfering with the mailer. Every time a guest account is created, the mailer will send an email to a non-existing email.
I am having trouble figuring out how to exclude the guests from the mailer.
user.rb:
after_create :send_welcome_mail
def send_welcome_mail
UserMailer.welcome_email(self).deliver
end
mailers/user_mailer.rb:
class UserMailer < ActionMailer::Base
default from: "[email protected]"
def welcome_email(user)
@user = user
mail(:to => user.email, :subject => "Welcome!")
end
end
application_controller.rb (guest creation):
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
I'm sure this is easy, but I am still new to rails and am a bit confused on the best way to go about this. Let me know if you need any other code.