Kevin Sylvestre Kevin Sylvestre - 1 month ago 4
Ruby Question

Rails Subdomain in Host Being Replaced

Given the following

config/routes.rb
:

constraints subdomain: 'subdomain' do
get 'path', to: 'main#index', as: :sample
end


The following works:

Rails.application.routes.url_helpers.sample_url(host: "a.b")
# "http://subdomain.a.b/path"


The following fails:

Rails.application.routes.url_helpers.sample_url(host: "a.b.c")
# "http://subdomain.b.c/path"


Any way to fix it so subdomains don't replace existing subdomains in the host but instead are linked (i.e.
http://subdomain.a.b.c/path
)? I realize I can change the subdomain in the route to be
subdomain.a
- but that'd be a bit of a pain to maintain for multiple subdomains / deployments.

Answer

Looks like you need to examine tld_length:

:tld_length - Number of labels the TLD id composed of, only used if :subdomain or :domain are supplied. Defaults to ActionDispatch::Http::URL.tld_length, which in turn defaults to 1.

I'll test the specifics, but the issue looks like Rails is only allowing a tld (top level domain) length of 1, which means that you can only have a subdomain and 1 "other" element (subdomain.b.c / subdomain.a.b).

The fix should be to expand the tld_length, which according to this answer, can be done in the config settings /config/application.rb:

# config/application.rb
config.action_dispatch.tld_length = 2

Tests

Without tld_length:

c:\Dev\Apps\torches>rails c
Loading development environment (Rails 5.0.0.1)
irb(main):001:0> Rails.application.routes.url_helpers.sample_url(host: "a.b")
=> "http://subdomain.a.b/path"
irb(main):002:0> Rails.application.routes.url_helpers.sample_url(host: "a.b.c")
=> "http://subdomain.b.c/path"
irb(main):003:0>

With tld_length:

c:\Dev\Apps\torches>rails c
Loading development environment (Rails 5.0.0.1)
irb(main):001:0> Rails.application.routes.url_helpers.sample_url(host: "a.b")
=> "http://subdomain.a.b/path"
irb(main):002:0> Rails.application.routes.url_helpers.sample_url(host: "a.b.c")
=> "http://subdomain.a.b.c/path"
irb(main):003:0>
Comments