【问题标题】:How to generate correct URLs in mailer templates?如何在邮件模板中生成正确的 URL?
【发布时间】:2012-02-08 23:43:08
【问题描述】:

我正在使用 Ruby on Rails 3.1.0,我想在 HTML 电子邮件消息中正确生成 URL。在我设置的环境文件中

config.action_mailer.default_url_options = { :host => 'my_site.org' }

在电子邮件视图文件 (.html.erb) 我声明

<%= link_to @user.name, users_url(@user) %>

当我查看收到的电子邮件时,生成的 URL 是http://users/1,当然不正确。那么,如何在邮件模板中生成正确的 URL,以便在正文中包含 http://my_site.org/users/1 链接?


我还尝试在我的mailer.rb 文件中设置default_url_options

class MyCustom::Mailer < ActionMailer::Base
  default_url_options[:host] = 'my_site.org'

  def test_sending
    ...
  end
end

但它不起作用。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 email mailer


    【解决方案1】:

    users_path 是相对路径 (/users/1)。对于电子邮件,您需要绝对路径,因此请使用users_url(@user),这将提供http://myapp.com/users/1

    【讨论】:

    • 如果我使用的路由没有thing_urlthing_path等辅助方法怎么办?
    【解决方案2】:

    您的 action_mailer 设置正确。

    但您应该使用 _url 而不是 _path 作为链接地址,

    <%= link_to @user.name, users_url(@user) %>
    

    【讨论】:

    • 你说得对,但为了公平起见,我会接受第一个答案。还是谢谢你。
    【解决方案3】:

    看到你设置了配置选项。为确保它使用绝对路径,请使用:

    <%= link_to, "My Profile", users_url(:only_path => false, @user) %>
    

    或在链接中专门设置主机:

    <%= link_to, "My Profile", users_url(:host => "example.com", @user) %>
    

    这里有解释:

    ActionView Helpers

    【讨论】:

      猜你喜欢
      • 2013-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-03
      • 2010-10-02
      • 1970-01-01
      • 2016-02-24
      相关资源
      最近更新 更多