2013-01-11 40 views
5

我很難搞清楚「Rails方式」以向郵件程序添加電子郵件確認URL。Rails:使自定義URL助手的行爲像內置_path&_url助手

我選擇不純粹以REST風格執行此操作,因爲使用文本電子郵件很困難,因爲它們不能PUT請求。

所以這裏是我的routes.rb:get 'confirm/:id' => 'Confirmations#confirm'

,並在我的郵件我喜歡把email_confirm_url(@user.email_token),我希望發生的URL。

我創造了一個幫手:

#app/helpers/confirmations_helper.rb 
module ConfirmationsHelper 
    def email_confirm_url(token) 
    "/confirm/#{token}" 
    end 
end 

這一切工作的排序,除非我打電話email_confirm_url(@user.email_token) ...

我真的得到: 「/confirm/abcdefg…

當我要的是: http://myhostname/confirm/abcdefg…

或正在開發中:http://localhost:3000/confirm/abcdefg…

如何讓我的URL幫助器更像在Rails中構建的<resource>_path<resource>_url幫助器?雖然現實,我想我真的只有需要_url

#Edit:我有這個在我的環境配置:

#config/environments/development.rb 
... 
config.action_mailer.default_url_options = { :host => "localhost:3000" } 

回答

0

爲了訪問請求對象,你應該在控制你的郵件實現該功能,並把它傳遞給一個模板變量。

應用程序/郵寄/ emailer.rb

@tracking_url = "http://#{request.host}:#{request.port}/confirm/#{token}" 

應用程序/視圖/電子郵件使用者/ template_name.html.erb

<%= link_to 'name', @tracking_url %> 
+0

'ActionView :: Template :: Error:未定義方法'host'for nil:NilClass'我想我記得有些東西在Mailer中無法訪問'host'或'host_with_port'!任何方式在這個? – Meltemi

+0

基於上述評論更新了答案,讓我知道如果這有效。 – zarazan

0

關於使用已經存在的URL加上串聯什麼?即你可以使用root_pathroot_url,然後你連接並且行爲和rails完全一樣!

例如,你可以這樣做:

def mystrangemethod_url(option1, option2) 
    "#{ root_url }/#{ option1 }/#{ option2 }" 
end 

和你做。容易和唯一的要求是設置設置您的根路徑routes.rb。此外,您在development.rb中設置的選項也可以在郵件程序中使用。

+0

我認爲Q更像是如何從視圖中透明地訪問'mystrangemethod_url'。 – mlt

相關問題