Rails: generate a full URL in an ActionMailer view

Viewed 19928

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?

5 Answers

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.

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

To generate url, try this

Rails.application.routes.url_helpers.user_url(User.first.id, host: 'yourhost.io')

this will generate url like this:

http://yourhost.io/users/1

As well you can pass some params

expires = Time.now + 2.days
params = {expires: expires}
u = User.first.id

Rails.application.routes.url_helpers.user_url(u, params, host: 'host.com')

will generate:

http://yourhost.io/users/1.expires=2018-08-12+15%253A52%253A15+%252B0300

so you can werifi in action if link is not expired

Related