Marc
Marc

Reputation: 1185

Why is my instance variable not being set in my action mailer's view?

For some reason my instance variables aren't being set in this ActionMailer. Other ActionMailers seem to work fine. Any ideas what might be causing this? Is UserMailer a restricted word perpahps?

Using rails 3.1

# app/mailers/user_mailer.rb

class UserMailer < ActionMailer::Base
  default from: 'My Name <[email protected]>'

  def registration_confirmation(user)  
    # Don't send email if we don't have an email address to send it to or the user is already confirmed 
    return unless user and user.email and not user.confirmed_at

    # Set global variable for mail view
    @my_message = 'Hello world!'

    # Send email
    mail(to: "#{user.name} <#{user.email}>", subject: 'Please confirm your email address')  
  end

end


# app/views/user_mailer/registration_confirmation.text.erb

Hello who? <%= @my_message %> # Simply returns 'Hello who? '

Upvotes: 1

Views: 494

Answers (2)

Sri Murthy Upadhyayula
Sri Murthy Upadhyayula

Reputation: 25908

You will have to restart your services and Workers if any for the changes to reflect.

Upvotes: 0

Marc
Marc

Reputation: 1185

Turns out this line:

return unless user and user.email and not user.confirmed_at

did not abort sending the email. Instead it just aborts the UserMailer code you see above and goes straight to the view which is now referring to an instance variable which hasn't been set. So in essence an ActionMailer works exactly like a regular controller.

To solve this issue I've moved the conditions that check whether to send the email to the place where I run the UserMailer command.

Upvotes: 1

Related Questions