This controller creates a user and sends a welcome email immediately after saving. The mailer defines the email details.
Ruby on Rails
class UsersController < ApplicationController
def create
@user = User.new(user_params)
if @user.save
UserMailer.welcome_email(@user).deliver_now
redirect_to root_path, notice: "Welcome email sent!"else
render :new
end
end
private
def user_params
params.require(:user).permit(:email, :password, :password_confirmation)
end
end
class UserMailer < ApplicationMailer
def welcome_email(user)
@user = user
mail(to: @user.email, subject: "Welcome to Our App")
end
end
OutputSuccess
Important Notes
Use deliver_later to send emails asynchronously and avoid slowing down user actions.
Keep email sending logic in mailers, not controllers, for cleaner code.
Always test emails in development using tools like Letter Opener or Mailcatcher.
Summary
Controllers trigger emails by calling mailer methods with data.
Use deliver_now for immediate sending, deliver_later for background jobs.
Keep email content and setup inside mailers, not controllers.
Practice
(1/5)
1. What is the main role of a controller when sending emails in Rails?
easy
A. To call the mailer method and trigger the email sending
B. To write the email content and layout
C. To configure the SMTP settings
D. To store email templates in the database
Solution
Step 1: Understand controller responsibility
Controllers handle user requests and trigger actions like sending emails by calling mailer methods.
Step 2: Identify mailer role
Mailers contain email content and setup, not controllers.
Final Answer:
To call the mailer method and trigger the email sending -> Option A
2. Which of the following is the correct syntax to send an email immediately from a controller using a mailer named UserMailer and a method welcome_email?
easy
A. UserMailer.welcome_email.deliver_later(params[:user])
B. UserMailer.welcome_email(params[:user]).deliver_now
C. UserMailer.deliver_now.welcome_email(params[:user])
D. UserMailer.welcome_email(params[:user]).send_now
Solution
Step 1: Identify mailer method call
The mailer method is called with parameters: UserMailer.welcome_email(params[:user]).
Step 2: Use correct delivery method
To send immediately, use deliver_now after the mailer method call.
Final Answer:
UserMailer.welcome_email(params[:user]).deliver_now -> Option B
Quick Check:
Immediate send = deliver_now after mailer call [OK]
Hint: Call mailer method then add .deliver_now for immediate send [OK]