5

$ rails -v Rails 4.2.1

$ ruby -v ruby 2.2.2p95 (2015-04-13 revision > 50295) [x86_64-linux]

I am building an API for a mobile app, which will have an admin interface to it. What i'm attempting to do, is run this through nginx using unicorn ( which I have running on my dev environment)

I have 2 domains routed to the exact same rails project. These domains are: api.project.dev and admin.api.project.dev

I've read this: http://guides.rubyonrails.org/routing.html#advanced-constraints

and tried: Separate Domain for Namespaced Routes in Rails 4 ( see answer )

I've tried a few other things to try and get this to work, the only thing that comes up ( for either sub-domain ) is:

Invalid route name, already in use: 'root'

My current implementation of this is:

class DomainConstraint
  def initialize(domain)
    @domains = domain
  end

  def matches?(request)
    @domains.include? request.domain
  end
end

and

require 'domain_constraint'
Rails.application.routes.draw do
  resources :statuses
  constraints (DomainConstraint.new('api.project.dev')) do
    root :to => 'statuses#index'
  end

  constraints(DomainConstraint.new('admin.api.project.dev')) do
    root :to => 'statuses#new'
  end
end

keep in mind that the roots are different pages only for now, but ultimately will be completely different systems.

Not quite sure where to go from here in order to get this functioning as I would hope.

Community
  • 1
  • 1
Justin
  • 2,131
  • 4
  • 24
  • 41

2 Answers2

6

With the fine help of the great people in #RubyOnRails on irc I got this figured out. So thanks crankharder and sevenseacat for your input and advice.

What I ended up with was this:

class DomainConstraint
  def initialize(domain)
    @domains = domain
  end

  def matches?(request)
    @domains.include? request.host
  end
end

and:

require 'domain_constraint'
Rails.application.routes.draw do

  constraints DomainConstraint.new('api.project.dev') do
    resources :statuses
    root :to => 'statuses#index', as: 'api_root'
  end

  constraints DomainConstraint.new('admin.api.project.dev') do
    resources :statuses
    root :to => 'statuses#new'
  end
end
Justin
  • 2,131
  • 4
  • 24
  • 41
4

You can also constrain a route based on any method on the Request object that returns a String. http://guides.rubyonrails.org/routing.html#request-based-constraints

The methods available to Request include host, which could be used as follows:

  constraints host: 'api.project.dev' do
    resources :statuses
    root to: 'statuses#index', as: 'api_root'
  end

  constraints host: 'admin.api.project.dev' do
    resources :statuses
    root to: 'statuses#new'
  end
Eliot Sykes
  • 9,616
  • 6
  • 50
  • 64