如何在Rails 3 link_to语句中包含完整路径?
我试图将一个Rails link_to语句放在包含完整路径的Mailer电子邮件中(即 – http:// localhost / contacts / id / confirm )。 我正在尝试的link_to语句在我的标准View in / pages / options中工作,但不在Mailer电子邮件中。
这是我的/ pages / options控制器代码:
class PagesController < ApplicationController def options end end
这是页面/选项查看:
"contacts", :action => "confirm", :only_path => false, :id => 17 %>
当我将此链接放入以下邮件程序(welcome_email.html.rb)时,我收到以下错误。 任何有关这方面的帮助将不胜感激。
"contacts", :action => "confirm", :only_path => false, :id => 17 %>
错误消息:
RuntimeError in Contacts#create Showing C:/Documents and Settings/Corey Quillen/My Documents/Dev/Dev Projects/my_project Project/my_project/app/views/user_mailer/welcome_email.html.erb where line #7 raised: Missing host to link to! Please provide :host parameter or set default_url_options[:host] Extracted source (around line #7): 4: 5: 6: 7: "contacts", :action => "confirm", :only_path => false, :id => 17 %> 8: 9:
因为邮件程序不在响应堆栈中运行,所以他们不知道从哪个主机调用它们:这就是你遇到这个错误的原因。 它很容易修复,更改代码以包含主机:
<%= link_to "here", :controller => "contacts", :action => "confirm", :only_path => false, :id => 17, :host => "example.com" %>
您还可以通过指定以下内容,在application.rb(或任何环境)内基于每个应用程序设置默认主机:
config.action_mailer.default_url_options = { :host => "example.com" }
有关ActionMailer的完整文档以及出现此问题的原因,请查看ActionMailer文档 。
第一步:
#config/environments/production.rb config.action_mailer.default_url_options = { :host => 'www.example.com' } #config/environments/development.rb config.action_mailer.default_url_options = { :host => 'localhost:3000' }
第二步:
<%= link_to "here", confirm_contacts_url(17) %>
基于当前指南http://guides.rubyonrails.org/action_mailer_basics.html#generating-urls-in-action-mailer-views ,我认为最好的方法是在环境配置文件中使用url_for并配置主机。 或者更好的是使用名称路线。
命名路由的示例
link_to @user.fullname, user_url(@user)
您需要使用link_to
提供:host
选项。
您还可以将config / environments / * .rb文件中的config.action_mailer.default_url_options
设置为适当的设置,以便在所有邮件程序中为link_to选择它们
例如 –
在config / environments / production.rb中
config.action_mailer.default_url_options = { :host => 'www.example.com' }
我认为在以电子邮件格式使用主机时,需要在主机中传递主机。 我记得在遇到类似问题时使用此页面: http : //www.cherpec.com/2009/06/missing-host-to-link-to-please-provide-host-parameter-or-set-default_url_optionshost/
这里有一篇关于它的SOpost也有不同的看法
如果完整URL始终与用户的请求匹配,您也可以使用actionmailer-with-request
gem将请求转发给动作邮件程序,然后您可以在邮件模板中引用请求,如:
<%= link_to "log into the admin page", request.base_url + admin_root_path %>