Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Routes in Engine mounted on subdomain do not inherit the constraints

Setup

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'}

The Problem

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

tl;dr

How can I get the engine's mounting constraints passed to its named routes?

EDIT: A Workaround

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

EDIT 2: A much less desirable workaround

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.

like image 953
Aaron Avatar asked May 23 '14 12:05

Aaron


1 Answers

@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).

like image 134
pnomolos Avatar answered Nov 04 '22 05:11

pnomolos