简体   繁体   English

如何在Ruby on Rails中使用带有邮件程序的实例变量?

[英]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.

相关问题 Ruby/Rails:你如何定制 Devise 的邮件模板? - Ruby/Rails: How do you customize the mailer templates of Devise? 是否可以在 rails mailer 的主题中使用实例或变量,以及如何使用:) - is it possible to use an instance or variable in the subject of rails mailer and how please :) Ruby On Rails:Sidekiq:实例变量@organisation在邮件布局中不可用 - Ruby On Rails : Sidekiq : Instance variable @organisation not available in mailer-layout 如何在Ruby on Rails的实例变量中测试某个值? - How can you test if a certain value is in an instance variable in Ruby on Rails? 如何在Ruby on Rails的模型类中引用模型的实例? - How do you refer an instance of a model in model class in Ruby on Rails? Ruby on Rails 2.3.8:测试:如何设置实例变量以在整个测试中使用? - Ruby on Rails 2.3.8: Testing: How do I set up an instance variable to use throughout my tests? 如何在Rails中传递实例变量来设计自定义邮件程序? - How to pass instance variable to devise custom mailer in Rails? 如何在rails上的ruby中为实例变量附加一些值? - How do i append some value to an instance variable in ruby on rails? 如何将变量添加到全局范围? (红宝石) - How do you add a variable to the global scope? (ruby on rails) 您如何测试Rails邮件程序凭据是否有效? - how do you test that Rails mailer credentials are valid?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM