开发者

Use of polymorphic_url in action mailer to get a full path

开发者 https://www.devze.com 2023-03-29 04:31 出处:网络
I have nested resources in my rails application which belong to groups. These items all have comments, and as such the comment file looks as follows:

I have nested resources in my rails application which belong to groups. These items all have comments, and as such the comment file looks as follows:

app/models/comment.rb

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

I need an ActionMailer which sends the user a link to the item, nested within its specific group. This however has left me banging my head against the wall as how to get the full path into the URL for the link. This is because url_for, when given a polymorphic object calls polymorphic_url on the object, but does not path the options of :only_path => false as the polymorphic_url doesn't take said option. Even in the non-nested resource (second link) it still only gives a path

Currently my mailer view looks as follows:

views/interaction_mailer/new_comment.html.erb

Hey <%= @user.name %>!<br />
<br />
<%= @comment.user.name %> just c开发者_C百科ommented 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 />

As I said, this doesn't give me a full path, but instead just a relative one.

Am I missing something? Is there a way to easily get the full path in this email?

PS my config/environments/development.rb file has the following:

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


I'm not sure if I'm understanding. Why is it a problem if polymorphic_url doesn't accept :only_path? Don't you want the full url in the email?

Why not simply call polymorphic_url([@item.group, @item])?

This should return the full URL, which is what you want, right?

The 2nd link isn't constructed correctly. You're passing the object as the 2nd arg, and only_path as the 3rd, which is being interperted as HTML options. The ActionView url_for helper forces path when using polymorphic routes (the opposite of ActionController's url_for... go figure), but you can simply call polymorphic_url to get at the URL in this case.

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

... should give you the URL.


Actually as it turned out some of the polymorphic_urls were even necessary as that is only necessary when you need to go to a controller for the polymorphic item, not if the item you are getting happens to come from a polymorphic object. As such the code cleans up to the following:

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 />
0

精彩评论

暂无评论...
验证码 换一张
取 消