Missing host to link to! Please provide :host parameter or set default_url_options[:host]

Problem:
Missing host to link to! Please provide :host parameter or set default_url_options[:host] when sending emails.

Solution:
You can pass host parameter to url functions, but it’s cleaner to configure it with a before_filter globally in your application_controller.rb:

  # application_controller.rb
  before_filter :mailer_set_url_options
 
  ...
 
  def mailer_set_url_options
    ActionMailer::Base.default_url_options[:host] = request.host_with_port
  end

9 comments ↓

#1 Lau on 11.29.09 at 8:27 am

Thanks !! :-)
solved my problem.

#2 Sandy on 02.02.10 at 2:36 am

Or put it in environment.rb

config.action_mailer.default_url_options = { :host => “example.com” }

#3 Phillip on 04.23.10 at 5:19 pm

@Sandy,

While that would work, the before_filter approach has the added benefit of being dynamic to the environment Rails is currently running in. This gives you the flexibility to have links in development point to development, not production.

#4 Francesco on 04.24.10 at 8:10 am

Hello,

thanks for the infos, you solved my issue, now I’m using this in my application.rb and it works well for my needs.

config.action_mailer.default_url_options = { :host => Rails.env == “production” ? ‘domain.com’ : ‘localhost:3000′ }

#5 Keikun17 on 08.31.10 at 7:01 am

Francesco, it’s cleaner if you just let the environtment configs handle the default_url_options

#6 Sandy on 11.19.10 at 8:41 am

@Phillip
That is why there are environment specific config files…

development.rb
production.rb
test.rb

#7 Jason on 12.21.10 at 1:54 am

@Sandy
But, wouldn’t those be hard-coded values? The before_filter approach doesn’t require code changes when the application moves or is deployed in on additional host.

#8 Cory Schires on 02.16.11 at 8:19 pm

@Jason

It’s true what you say about the benefits of the before_filter being dynamic. But more importantly, we expect configuration details (like host settings) to be specified in the env files. That’s the convention. For example, that’s where devise tells you to place this info – not in a before filter.

Although your idea is good and the logic is sound, I think it’s better to follow the conventions. That way future developers know where to find things.

#9 Mark on 09.09.11 at 6:54 am

Another side-effect of putting the declaration in a before_filter is that it will be executed once for *every* request. Use the appropriate config environment files where it is run only *once* when the application starts.

Any cases with a valid reason to override the mail settings can still be done on an individual basis.

Leave a Comment