0

我的 user_mailer.rb:

class UserMailer < ActionMailer::Base
  default :from => "notifications@example.com"
  def welcome_email(user)
    @user = user
    @url  = "http://example.com/login"
    mail(:to => user.email,:subject => "Welcome to My Awesome Site") do |format|
      format.html
    end
  end
end

这就是我的 user_mailer.html.erb 的样子:

<!DOCTYPE html>
<html>
  <body>   
    <%= yield %> 
  </body>
</html>

我可以在 user_mailer.html.erb 中访问什么。我需要在哪里定义环境变量以便我可以在这里访问它?

4

2 回答 2

1

我猜你从这里拿你的例子?

您可以user_mailer.html.erb像对待视图一样对待,也可以像对待user_mailer.rb它的控制器一样对待。因此,如果您定义了一个实例变量@users,那么您可以在邮件中使用它。根据链接中的示例:

user_mailer.html.erb

<!DOCTYPE html>
<html>
  <head>
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
  </head>
  <body>
    <h1>Welcome to example.com, <%= @user.name %></h1>
    <p>
      You have successfully signed up to example.com,
      your username is: <%= @user.login %>.<br/>
    </p>
    <p>
      To login to the site, just follow this link: <%= @url %>.
    </p>
    <p>Thanks for joining and have a great day!</p>
  </body>
</html>

您也可以使用帮助程序,因此没有理由像这样对 URL 进行硬编码,而是可以使用sign_in_url(或您拥有的登录路径的任何路径)。

请注意,在电子邮件中您应该始终使用something_url而不是something_pathroot_url等等)

您应该在welcome_email方法中定义变量:

def welcome_email(user)
  @user = user
  @time = Time.now
  @slogan = "My App's slogan"
  ...
  mail(:to => user.email,:subject => "Welcome to My Awesome Site") do |format|
    format.html
  end
end
于 2013-05-20T05:13:54.290 回答
0

您可以访问视图部分中的任何实例变量。所以在你的情况下,

 @user and @url are accessible in user_mailer.html.erb
于 2013-05-20T06:01:51.793 回答