Search code examples
ruby-on-railsrubymailer

Passing Variable into Rails Mailer


Hey there Stack Users,

I have been frustrated with this problem for about two hours now and don't know what I am doing wrong. I am calling a method send_intro_emailon an update action for a User. The send_intro_email method calls a NotificationMailer method named intro_email(user).

The problem I am having is the data for user is being passed all the way until the point of where it is used inside .erb email. I tested it and it actually is being passed but don't know why I can't use it inside the email itself.

Files:

notificaion_mailer.rb

def intro_email(user)
   puts user # works
   mail(to: "email", from: "email2", subject: "THIS IS A TEST")
end

User.rb

def send_intro_email 
  NotificationMailer.intro_email(self).deliver
end

intro_email.erb

The users name is <%= user.name %>.

I can show an error message later when I get on my other PC if needed. Thank you so much for any help.


Solution

  • Well, you are using local variable user, which has scope only to the method you have defined. You have to use instance variable @user as an example. So changes are to be done like :

    def intro_email(user)
       @user = user
       mail(to: "email", from: "email2", subject: "THIS IS A TEST")
    end
    

    Then inside the view use @user. Like

    The users name is <%= @user.name %>.