Rails: generate a full URL in an ActionMailer view

19,746

Solution 1

To solve the problem to pass a host for generating URLs in ActionMailer, check out this plugin and the reason why I wrote it.

To solve the first issue, use named routes when applicable. Instead of

<%= url_for :controller => 'login', :action => 'verify', :guid => @user.new_user.guid, :only_path => false, :host => 'http://plantality.com' %>

assuming the route is called login, use

<%= login_url(:guid => @user.new_user.guid) %>

Note, I'm using login_url, not login_path.

Solution 2

I'm not sure if it is what you want but in config/environments/development.rb you can specify default options for mailer urls

config.action_mailer.default_url_options = {
  :host => "your.host.org",
  :port => 3000
}

you can do the same in config/environments/production.rb

Solution 3

I don't know why the previous solutions seem so complicated, but since I'm here why not give my 2 cents...

Go to /config/environments and add:

config.absolute_site_url = 'your site url'

for the respective environment (ie. in development.rb, test.rb, or production.rb). Restart web server.

This allows you to call Rails.application.config.absolute_site_url to get the desired URL. No need for plugins or weird cheat, just store the site url as an application wide variable.

Solution 4

I think its not 100% correct way but this can also be a solution :

See the Using asset hosts section in the documentation. You need to specify an asset_host. You can also construct it dynamically from the request chaining "#{request.protocol}#{request.host_with_port}/login/?guid=#{@user.new_user.guid}"

Share:
19,746

Related videos on Youtube

Mike Sutton
Author by

Mike Sutton

Updated on April 16, 2022

Comments

  • Mike Sutton
    Mike Sutton about 2 years

    I'm using ActionMailer to send a sign up confirmation email. The email needs to contain a link back to the site to verify the user, but I can't persuade Rails to generate a full URL (including the domain etc).

    I'm using:

    <%= url_for :controller => 'login', :action => 'verify', :guid => @user.new_user.guid, :only_path => false, :host => 'http://plantality.com' %>
    

    in my view

    Part b:

    In development mode Rails gripes if I don't specify the host explicilty in the link above. But I don't want to do this in production. Any solutions?

  • Kylo
    Kylo over 14 years
    I'm using syntax that you've provided without :host part, and I'm getting full URLs. :only_path => false is important.
  • Arnold Roa
    Arnold Roa over 7 years
    request exists in an action mailer view? what if is a background job?