url_for not using default_url_options[:host] value

actionmailer, ruby-on-rails

Solution

The documentation is pretty clear on this

When you decide to set a default :host for your mailers, then you need to make sure to use the :only_path => false option when using url_for. Since the url_for view helper will generate relative URLs by default when a :host option isn’t explicitly provided, passing :only_path => false will ensure that absolute URLs are generated.

You could create your own helper to use instead of the `url_for` to force `:only_path` to be `false`

def your_url_for(options = {})
  options.reverse_merge! only_path: false
  url_for(options)
end

You could also monkey patch rails to force this as the default, but that's left up to you :)

This all would be in addition to adding

config.action_mailer.default_url_options = { host: "YOUR HOST" }

to `config/application.rb` or equivalent.

Problem

I've got a view for an ActionMailer that includes a few different links. I'm running it on localhost:3000 right now, and so I've set that as such in a file called `setup_mail.rb` in app/initializers (as indicated here): ``` ActionMailer::Base.default_url_options[:host] = "localhost:3000" ``` When I go to use `url_for` in the view, it doesn't seem to pull this value. If I then add `:host => "localhost:3000"` to each `url_for` tag, they work properly. But they don't work without that included. I have another tag, `project_url`, which is as it appears: a link to a specified Project. This functions, including the host value, with just `project_url(@project)`. Why would one work but not the other? From everything I've read, setting the `default_url_options[:host]` in an initializer should allow me to omit the `:host` value in the `url_for` tag. Obviously, it's not the worst thing in the world to just add that value, but it seems unnecessary and it means that when I eventually host the project somewhere I'll have to go through and change that value all over the place. But worse than that, it's something that I don't understand. I'm still learning as I go here and so I'd like to know what I'm doing wrong.

Original source