Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include subdomain for constrained route in Rails url helper

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

My 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

Maybe I need to override the url helpers manually? How would I approach that (accessing the routes etc)?

Edit: 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, I would prefer not having to specify this all over the code.

like image 821
Baversjo Avatar asked May 09 '12 02:05

Baversjo


1 Answers

Using "defaults" as shown below will make rails url helpers output the correct subdomain.

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
like image 76
Baversjo Avatar answered Nov 03 '22 04:11

Baversjo