3

I created an instance variable (@user) in the model of a mailer and want to access it in the view? But it's giving me an an error (@user = nil). What's the best way to pass a variable to view (the email body)?

Thanks, Chirag

Chirag Patel
  • 5,819
  • 8
  • 35
  • 38

3 Answers3

7

If you want to access an instance variable in your mailer template then in your mailer model add

@body[:user] = user_object

The above would create an instance variable @user that can be accessed in your view. You should be able to access user object in your mailer view by doing

@user

The docs here have examples of alternative ways if you are using multiple formats (text/html).

nas
  • 3,676
  • 19
  • 19
  • 1
    Hi, I am a little confused the examples show directly assigning the value @account = recipient for example....does that work instead? It's not for me...so wondering whether your way of @body[:user] is the way to create @user. – Satchel Jun 19 '11 at 08:38
  • 2
    this gives me the expected "you tried to call [] on nil (@body)" error. @nas - do you advise that this line be @body[:user] = user_object defined above and outside the methods in the mailer model? – Sean Ahrens Aug 26 '11 at 10:06
4

I Rails 3 the process is similar:

@user = user_object

The above would create an instance variable @user that can be accessed in your view. You should be able to access user object in your mailer view by doing

@user

Note that you need to set this variable before the

mail(:from => "info@domain.info", :to => recipient, :subject => "Subject")
MacTeo
  • 2,656
  • 1
  • 20
  • 23
2

To pass a variable to the view/email body, you send them in via the body method :-) So, for example, body :account => recipient would result in an instance variable @account with the value of recipient being accessible in the view.

Thorbjørn Hermansen
  • 3,522
  • 1
  • 21
  • 12