Reputation: 5812
I have a Rails application, where I have a visitors_controller for homepage and a contacts_controller for contact form. My website has to be single-paged, so I'm invoking Contact.new inside visitors controller.
When the submit action is executed, in contacts_controller the user is redirected to root_path
, in save or in error.
There is an email field which is used to deliver the user a mail. The setback happens when the user doesn't fill it and for some reason the user is redirected to contacts_path instead of root_path.
It throws the following error: An SMTP To address is required to send a message. Set the message smtp_envelope_to, to, cc, or bcc address.
This is the function that reads the email and delivers to the user: VisitorMailer.landing_form_notify_user(@contact).deliver_now
Not filling it redirects the user to contacts_index.
Question: How can I stop executing this function if the user hasn't filled the email field?
app/controllers/visitors_controller.rb
class VisitorsController < ApplicationController
def index
@contact = Contact.new
end
end
app/controllers/contacts_controller.rb
def create
@contact = Contact.new(contact_params)
respond_to do |format|
if @contact.save
VisitorMailer.landing_form_notify_user(@contact).deliver_now
format.html { redirect_to root_path, notice: 'Good' }
format.json { render root_path, status: :created, location: @contact }
else
format.html { render root_path }
format.json { render json: @contact.errors, status: :unprocessable_entity }
end
end
end
app/mailers/visitors_mailer.rb
class VisitorMailer < ApplicationMailer
default :from => "[email protected]"
def landing_form_notify_user(user)
@user = user
email_with_name = %("#{@user.name}" <#{@user.email}>)
mail(
to: "#{@user.email}",
subject: "#{@user.name}" + ', hi.'
)
end
end
Upvotes: 1
Views: 39
Reputation: 3545
If you don't want to attempt to send an email if the email address is missing, all you have to do is check for an email address before you call the mailer.
def create
@contact = Contact.new(contact_params)
respond_to do |format|
if @contact.save
unless @contact.email.blank?
VisitorMailer.landing_form_notify_user(@contact).deliver_now
end
# more stuff to do if save succeeds
else
# stuff to do if save fails
end
end
end
Upvotes: 2
Reputation: 7779
VisitorMailer.landing_form_notify_user(@contact).deliver_now if @contact.email.present?
Upvotes: 1