Wrong subdomain for constrained route in url helper #6224

Closed
baversjo opened this Issue May 9, 2012 · 3 comments

2 participants

@baversjo

Say I have the following routes that are constrained to specific subdomains:

App::Application.routes.draw do
  constraints :subdomain => "admin" do
    scope :module => "backend", :as => "backend" do
      resources :signups
      root :to => "signups#index"
    end
  end
  constraints :subdomain => "www" do
    resources :main
    root :to => "main#landing"
  end
end

The problem is that root_url and backend_root_url both returns a url on the current subdomain: "http://current-subdomain.lvh.me/" instead the subdomain specific for the resource. I would like root_url to return "http://www.lvh.me/" and backend_root_url to return "http://admin.lvh.me/" (the behavior should be the same for all resources under the subdomain).

I have tried to accomplish this in rails 3.2 by setting the url options in various places, one being url_options in application controller:

class ApplicationController < ActionController::Base
  def url_options
    {host: "lvh.me", only_path: false}.merge(super)
  end
end

I'm able to get the correct result using root_url(:subdomain => "admin") which returns "http://admin.lvh.me/" regardless of the current subdomain. However, this is not very DRY.

@pixeltrix
Ruby on Rails member

Routing constraints are for url recognition - if you want to restrict certain routes to specific subdomains then you can use defaults, e.g:

App::Application.routes.draw do
  constraints :subdomain => "admin" do
    scope :module => "backend", :as => "backend" do
      defaults :subdomain => "admin" do
        resources :signups
        root :to => "signups#index", :subdomain => "admin"
      end
    end
  end

  constraints :subdomain => "www" do
    defaults :subdomain => "www" do
      resources :main
      root :to => "main#landing"
    end
  end
end
>> app.root_url
=> "http://www.example.com/"
>> app.backend_root_url
=> "http://admin.example.com/"
@pixeltrix pixeltrix closed this May 9, 2012
@baversjo

thanks, that works!

@pixeltrix pixeltrix reopened this May 10, 2012
@pixeltrix
Ruby on Rails member

Reopening this as I'm going to enhance constraints so that it will automatically set defaults where appropriate

@pixeltrix pixeltrix was assigned May 10, 2012
@pixeltrix pixeltrix closed this May 11, 2012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment