Kelly
Kelly

Reputation: 469

Action Mailer Variable Definition Explanation

I'm trying to fully understand a line of code in the action mailer that is shown in every documentation but not really explained.

def welcome_email(user)
 @user = user #don't understand exactly which user this is
 mail(to: @user.email, subject: 'Do you have any spam?')
end

I thought you had to define that variable like User.find(params[:id]) or User.first or something else that retrieves a specific user. What does plain 'user' mean in this context?

Thanks for your help with this beginner level question.

Upvotes: 1

Views: 29

Answers (1)

Prakash Murthy
Prakash Murthy

Reputation: 13067

@user = user

This line is setting the value of @user instance variable to user which is being passed as a variable to the welcome_email method.

@user instance variable can be accessed in the views linked to this mailer.

Where-ever the welcome_email method is called, it is likely to have set the value of user using user = User.find(params[:id]) or user = User.first or something similar, and that user is passed in as a parameter with welcome_email(user) call.

Assuming the mailer is called Notifier, and the welcome email has to be sent when the user signs up, the following code is likely to be in the app/controllers/users_controller.rb file:

class UsersController < ApplicationController
  ...
  def create
    ...
    @user = ...
    Notifier.welcome_email(@user).deliver_now
    ...
  end
  ...
end

Upvotes: 1

Related Questions