ruby on rails - Route Constraints Not Working As Expected -


i hoped route constraints allow me have admin.example.com/widgets/ , example.com/admin/widgets/ same, url helper admin_widgets_path pointing correct 1 based on current subdomain. however, route helper seems point 1 or other regardless of constraints.

am doing wrong? bug? there better way solve problem?

a rails app example of problem has been published here, relevant details below.

my config/routes.rb

class subdomains   # domain starts 'admin.'   def self.admin?     -> (request) { request.host =~ /^admin\./ }   end    # other domain   def self.primary?     -> (request) { !admin?.(request) }   end end  rails.application.routes.draw   constraints(subdomains.primary?)     namespace :admin       resources :widgets     end   end    constraints(subdomains.admin?)     scope module: "admin", as: :admin       resources :widgets     end   end    root to: "admin/widgets#index" end 

my app/views/admin/widgets/index.html.erb

<%= link_to "widgets", admin_widgets_url %> 

in configuration, admin_widgets_url returns /admin/widgets/ isn't valid route on admin.example.com clicking link results in routing error on subdomain. if admin subdomain constraint block put first in routes, url helper returns /widgets/, breaking link on non-admin domain.

the routes otherwise work, not sure how url helpers point correct one.

your expectations wrong - rails reads entire routes definition part of setup phase. when route helpers created. constraint not evaluated until later when request matched.

rails splits distinct phases allow forking.

instead may need override route helpers.


Comments