How do you use an instance variable with mailer in Ruby on Rails?

狂风中的少年 提交于 2019-12-07 13:59:20

问题


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


回答1:


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).




回答2:


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")



回答3:


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.



来源:https://stackoverflow.com/questions/2122320/how-do-you-use-an-instance-variable-with-mailer-in-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!