i have rails application, have visitors_controller homepage , contacts_controller contact form. website has single-paged, i'm invoking contact.new inside visitors controller.
when submit action executed, in contacts_controller user redirected root_path
, in save or in error.
there email field used deliver user mail. setback happens when user doesn't fill , reason user redirected contacts_path instead of root_path.
it throws following error: an smtp address required send message. set message smtp_envelope_to, to, cc, or bcc address.
this function reads email , delivers user: visitormailer.landing_form_notify_user(@contact).deliver_now
not filling redirects user contacts_index.
question: how can stop executing function if user hasn't filled 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 |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 => "mygmail@gmail.com" 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
if don't want attempt send email if email address missing, have check email address before call mailer.
def create @contact = contact.new(contact_params) respond_to |format| if @contact.save unless @contact.email.blank? visitormailer.landing_form_notify_user(@contact).deliver_now end # more stuff if save succeeds else # stuff if save fails end end end
Comments
Post a Comment