Corey Kossack
Corey Kossack

Reputation: 3

Why do I get a NoMethodError in my ActionMailer?

I am trying to trigger emails with ActionMailer when users complete various actions within the website, such as creating a new status.

When I try to call the mailer in the create method of the Statuses controller, I get a NoMethodError:

undefined method 'email' for nil:NilClass

Can anyone help me figure out what is wrong?

Here is my code from within the statuses controller:

def create
  @status = current_user.statuses.new(params[:status])

  respond_to do |format|
    if @status.save
      UserMailer.status_confirmation(@user).deliver
      format.html { redirect_to @status, notice: 'Status was successfully created.' }
      format.json { render json: @status, status: :created, location: @status }
    else
      format.html { render action: "new" }
      format.json { render json: @status.errors, status: :unprocessable_entity }
    end
  end
end

Here's my UserMailer code:

class UserMailer < ActionMailer::Base

  default :from => "[email protected]"

  def status_confirmation(user)
    mail(:to => user.email, :subject => "Status Posted")
  end
end

Upvotes: 0

Views: 1421

Answers (1)

Dave Newton
Dave Newton

Reputation: 160201

You're passing in a null user (@user):

def create
  @status = current_user.statuses.new(params[:status])
  respond_to do |format|
    if @status.save
      # There's no @user here, unless it's initialized in a filter, etc.
      UserMailer.status_confirmation(@user).deliver

Did you mean current_user instead, or did you forget to initialize it (or forget some code)?

Upvotes: 0

Related Questions