2013-05-20 28 views
0

我user_mailer.rb:什麼是可從user_mailer.html.erb訪問的變量?

class UserMailer < ActionMailer::Base 
    default :from => "[email protected]" 
    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訪問。 我在哪裏需要定義的環境變量,這樣我可以在這裏訪問它?

回答

1

我猜你把從here你的榜樣?

你可以把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_path(所以root_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 
0

您可以訪問任何實例變量視圖部分。所以你的情況,

@user and @url are accessible in user_mailer.html.erb 
相關問題