Bug: direct routing paths with _path still require host

Let’s say you create a custom routing helper with the direct routing config method (Guide, API)

With route helpers, you always get a _url or _path variant. With ‘typical’ (not direct) route helpers, you can call the _path variant even in places where a hostname is not available for the _url variant. For instance:

Rails.application.routes.url_helpers.widget_index_path
# => '/widgets/'

# but, expected: 

Rails.application.routes.url_helpers.widget_index_url
# raises: ArgumentError,  Missing host to link to! Please provide the :host
# parameter, set default_url_options[:host], or set :only_path to true

Great, this all makes sense.

But with a route helper you created with direct, the _path variant always requires the host to be available from context too:

Rails.application.routes.url_helpers.my_direct_path
# raises: ArgumentError,  Missing host to link to! Please provide the :host
# parameter, set default_url_options[:host], or set :only_path to true

And in fact, I believe there’s no real way to “provide the :host parameter” in this case, or to set :only_path to true. You need to use some mechanism of setting default_url_options[:host] to be able to call the direct routing helper _path variant without a host in context, even though the host won’t ultimately be included in the URL.

After debugging the stack trace: This is happening because the implementation of resolving direct route helpers ends up always first trying to create the complete absolute url (the _url) variant, and then extracting only the (relative) path component from it in cases where only a relative url (_path) variant is needed. So this requires the host to be available even in cases where it’s going to be thrown out.

https://github.com/rails/rails/blob/main/actionpack/lib/action_dispatch/routing/route_set.rb#L623-L641

While convenient, the logic of “always make a full url, then just throw away the protocol/host if only a _path was needed” results in this problem.

You ought to be able to call the _path variant without a host being present, right? I am pretty sure this is a bug.

I am considering filing this as a bug in GH issue – or even taking the time to make a PR to fix it.

But because of past experiences where I’ve spent a bunch of time on an Issue or PR but only had it sit there ignored until auto-closed, I decided to start here in the forum, and see what attention/feedback/advice I get.

Any thoughts?

This is some excellent detective work, and I agree, it would be useful. One thing that seems to get the Powers That Be to take notice is good promotion of the problem and solution. If you can think of a way (refinements? monkey-patching?) to build a Gem that fixes the problem, and then promote the heck out of it, and only then put your PR in, you might find yourself with a quicker path to victory.

Thanks!

Walter