Search code examples
ruby-on-railsruby-on-rails-4routessubdomain

Subdomain argument is ignored in my links, so all links are prepend with request.subdomain


I have a Ruby on Rails 4 website that I wish to split up in domain.com and mysubdomain.domain.com. I am using lvh.me for testing.

My routes file:

MyApp::Application.routes.draw do
  scope "(:locale)", locale: /#{I18n.available_locales.join("|")}/ do

    get "first_page" => "pages#first_page", :as => :first_page

    constraints subdomain: "mysubdomain" do
      get "second_page" => "pages#second_page", :as => :second_page
    end

    root :to => 'pages#index'

  end
end

In my view file I have:

= link_to "First page",  first_page_path
= link_to "Second page", second_page_path(:subdomain => "mysubdomain")

But the subdomain argument is apparently ignored. Instead all links gets prepend with request.subdomain.

So if e.g. I am on:

http://mysubdomain.lvh.me:3000/second_page

Then the links on the webpage are as follows:

http://mysubdomain.lvh.me:3000/first_page   # Not as intended
http://mysubdomain.lvh.me:3000/second_page  # As intended

How to fix this?


Solution

  • The problem is you're using the _path helper and not the _url helper. The former generates a relative path so the site will use the current host where as the latter generates a full URL.

    = link_to "Second page", second_page_url(subdomain: "mysubdomain")
    

    should do what you're looking for.