Multi-tenancy and sub domain(lvh) with rails

Praaveen Vr
praaveen
Published in
2 min readNov 19, 2019

Simple multi-tenancy with the help of acts_as_tenant

multi-tenancy reference

lvh.me reference

Dynamic request matching

author.rb

class Author < ApplicationRecord
end

post.rb

class Post < ApplicationRecord
acts_as_tenant(:author)
end

From console

> Author.create(name: 'Rob')
> Author.create(name: 'David')
> ActsAsTenant.current_tenant = Author.find_by(name: 'Rob')
> Post.create(content: "Rob's article")
> Post.all

=> #<ActiveRecord::Relation [#<Post id: 1, content: "Rob's article", created_at: "2019-06-01 07:46:31", updated_at: "2019-06-01 07:46:31", author_id: 1>]>
> ActsAsTenant.current_tenant = Author.find_by(name: 'David')
> Post.all => #<ActiveRecord::Relation []>

routes.rb

Rails.application.routes.draw doconstraints(SubdomainRequired) do
resources :comments
resources :posts
end
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

config/intializers/subdomain_required.rb

class SubdomainRequired
def self.matches?(request)
subdomain = request.subdomains.first
tenant = Author.find_by subdomain: subdomain
subdomain.present? && tenant
end
end

application_controller.rb

class ApplicationController < ActionController::Base
protect_from_forgery with: :exception

set_current_tenant_through_filter
before_action :current_tenant_from_subdomain
def current_tenant_from_subdomain
tenant = Author.find_by subdomain: request.subdomains.first
set_current_tenant(tenant)
end
end

Console

#<ActiveRecord::Relation [
#<Author id: 1, name: "Rob", created_at: "2019-06-01 07:45:08", updated_at: "2019-06-01 10:16:27", subdomain: "drob">,
#<Author id: 2, name: "David", created_at: "2019-06-01 07:45:09", updated_at: "2019-06-01 10:16:42", subdomain: "dd">]><ActiveRecord::Relation [
#<Post id: 1, content: "Rob's article", created_at: "2019-06-01 07:46:31", updated_at: "2019-06-01 07:46:31", author_id: 1>,
#<Post id: 2, content: "David article", created_at: "2019-06-01 07:48:42", updated_at: "2019-06-01 07:48:42", author_id: 2>]>

open browser and hit

http://drob.lvh.me:3000/

http://drob.lvh.me:3000/posts

shows only Rob’s posts

http://dd.lvh.me:3000/posts

shows only David’s posts

above links will work

http://test.lvh.me:3000/posts
will not work no such subdomain

Sample code repo is here

--

--