Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Domain Constraints ( to serve multiple domains )

$ 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.

like image 875
Justin Avatar asked Dec 24 '22 20:12

Justin


1 Answers

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
like image 157
Justin Avatar answered Jan 05 '23 18:01

Justin