[英]How do you use an instance variable with mailer in Ruby on Rails?
I created an instance variable (@user) in the model of a mailer and want to access it in the view? 我在邮件程序的模型中创建了一个实例变量(@user),并希望在视图中访问它? But it's giving me an an error (@user = nil). 但它给了我一个错误(@user = nil)。 What's the best way to pass a variable to view (the email body)? 将变量传递给视图(电子邮件正文)的最佳方法是什么?
Thanks, Chirag 谢谢,奇拉格
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. 以上将创建一个可在您的视图中访问的实例变量@user。 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). 如果您使用多种格式(text / html), 这里的文档有替代方法的示例。
I Rails 3 the process is similar: I Rails 3的过程类似:
@user = user_object
The above would create an instance variable @user that can be accessed in your view. 以上将创建一个可在您的视图中访问的实例变量@user。 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")
要将变量传递给视图/电子邮件正文,您可以通过正文方法发送它们:-) 因此,例如 , body :account => recipient
将导致实例变量@account
,其中可以访问recipient
的值视图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.