Our current Rails app is made out of sub-apps that are mounted as engines. Typically these engines are mounted on a subdomain in the main routes.rb
file as follows
mount MySubApp::Engine => '/', as: :sub_app, constraints: {subdomain: 'sub_app'}
Routes within MySubApp
's routes.rb
file do not get the subdomain when using the named _url
helpers. For example the following in apps/my_sub_app/config/routes.rb
MySubApp::Engine.routes.draw do
resources :foos
end
gives us sub_app.foo_url(5)
but it results in
http://www.example.com/foos/5
when we want
http://sub_app.example.com/foos/5
How can I get the engine's mounting constraints passed to its named routes?
While I'd still prefer a better solution, the following will work. You can wrap all the routes in each of the sub apps routes.rb
files that could be mounted on a subdomain like so
MySubApp::Engine.routes.draw do
constraints Rails.application.routes.named_routes[:sub_app].constraints do
resources :foos
end
end
A commenter (since deleted?) pointed out you can pass a subdomain
option to the helpers but we'd like to avoid having to use sub_app.foo_url(5, {subdomain: 'sub_app'})
for every cross subdomain link. Even if we moved the subdomain name into an ENV var and made a wrapper, this is not DRY.
@Aaron not sure if you ever got this fixed, but look into the
config.action_dispatch.tld_length
setting (on the engine's config). I'm not sure how it'll react with engines, but in our case it lets us handle the case of sub-subdomains for our staging server (so when we use the _url
helpers with the staging server it correctly does subdomain.staging.domain.com
, rather than subdomain.domain.com
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With