0

I have a rails app where I want to send people an email when they sign up. The email has a link to their photos portal so they can get started adding photos, etc..

class MyMailer < ActionMailer::Base
  def welcome_email
    # ...

    link = photos_url  # => www.myapp.com/photos

    # ...
  end
end

The problem is that when I push my code to Heroku and run it live, that link doesn't generate as expected.

The photos_url returns the URL relative to the localhost and ends up generating myapp.herokuapp.com/photos, which is incorrect.

What's even stranger is that if I pause the code at that point with binding.pry and try to see what photos_url is returning, it correctly returns www.myapp.com/photos as expected.

Any thoughts on how to resolve this? I'd hate to have to construct the URL myself from scratch, because that means I have to do it for every environment (localhost, staging, production, etc...)

Thanks!

user2490003
  • 10,706
  • 17
  • 79
  • 155
  • 1
    Possible duplicate of [How do I configure the hostname for Rails ActionMailer?](http://stackoverflow.com/questions/798917/how-do-i-configure-the-hostname-for-rails-actionmailer) – Brad Werth Nov 15 '15 at 22:50

1 Answers1

0

ActionMailer isn't tied to the request/response cycle, thus it doesn't know what's the host the app is currently running on. Actually, emails are typically sent by some background worker processes which know nothing about the current request URL.

So to make it work you need to set the ActionMailer default_url_options.host option.

Add this into you config/environments/production.rb:

config.action_mailer.default_url_options = { host: 'www.yourapp.com' }
Dmitry Sokurenko
  • 6,042
  • 4
  • 32
  • 53
  • Ah I see! So I used `ActionMailer` for this example since it's well known, but in my particular case I'm using a service called Mandrill which allows you to hit its api and it sends an email. The job is processed in the background by Sidekiq. The same problem still exists though - the background worker process (Sidekiq) doesn't know the host. Is there a more general way to get the host? It sounds like I have to manually configure it for each environment. Thanks! – user2490003 Nov 15 '15 at 22:41
  • In general you can set the hostname using a environment variable, e.g. `APP_HOST=www.foo.com`, and then pass that variable to the mail-api specific method (not-sure which one for Mandrill). Also it may happen that Mandril has the host set somewhere in its settings UI. – Dmitry Sokurenko Nov 15 '15 at 22:48