在动作邮件程序中使用polymorphic_url来获取完整路径

时间:2011-08-20 02:09:30

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

我在rails应用程序中嵌套了属于组的资源。这些项目都有注释,因此注释文件如下所示:

应用程序/模型/ comment.rb

class Comment < ActiveRecord::Base
    belongs_to :item, :polymorphic => true
    ...
end

我需要一个ActionMailer,它向用户发送一个项目链接,嵌套在其特定组中。然而,这让我不知所措地如何获得链接的URL的完整路径。这是因为url_for,当给定一个多态对象时,会调用该对象上的polymorphic_url,但不会路径选择:only_path =&gt; false,因为polymorphic_url没有采用所述选项。即使在非嵌套资源(第二个链接)中,它仍然只提供路径

目前我的邮件程序视图如下所示:

视图/ interaction_mailer / new_comment.html.erb

Hey <%= @user.name %>!<br />
<br />
<%= @comment.user.name %> just commented on the <%= @item_string %> <%=  link_to @item.title, polymorphic_path([@item.group, @item]) %> in your group (<%= link_to @item.group.name,  @item.group, :only_path => false%>).<br />

正如我所说,这并没有给我一条完整的道路,而只是一条相对的道路。

我错过了什么吗?有没有办法轻松获得此电子邮件中的完整路径?

PS我的config / environments / development.rb文件包含以下内容:

config.action_mailer.default_url_options = {:host => 'localhost', :port => 3000}

2 个答案:

答案 0 :(得分:1)

我不确定我是否理解。如果polymorphic_url不接受:only_path,为什么会出现问题?你不想要电子邮件中的完整网址吗?

为什么不简单地拨打polymorphic_url([@item.group, @item])

这应该返回完整的URL,这就是你想要的,对吗?

第二个链接构造不正确。您将对象作为第二个arg传递,而only_path作为第三个参数传递,它作为HTML选项进行交互。 ActionView url_for帮助程序在使用多态路由时强制路径(与ActionController的url_for相反... go图),但在这种情况下,您只需调用polymorphic_url来获取URL。

<%= link_to @item.group.name, polymorphic_url(@item.group) %>

...应该为您提供网址。

答案 1 :(得分:0)

实际上,事实证明有些polymorphic_urls甚至是必要的,因为只有当你需要去控制器来获取多态项目时才需要,而不是你要获得的项目恰好来自多态对象。因此,代码可以清除以下内容:

Hey <%= @user.name %>!<br />
<br />
<%= @comment.user.name %> just commented on the <%= @item_string %> <%=  link_to @item.title, polymorphic_url([@item.group, @item]) %> in your group (<%= link_to @item.group.name,  group_url(@item.group) %>).<br />