Alex Rivera | Logout

Writing a multi-tenant Rails 3 app for deployment on Heroku

Asked 2011-05-06T20:25:10.073
13

I'm building a Rails 3 app for deployment on Heroku, and I'm wondering if there are any recommendations on how to handle multi-tenancy in my models. Half a year ago, there was a related question (#3776593) posted on here, but it didn't get many answers. I've also watched Guy Naor's presentation on writing multi-tenant applications with Rails, but it seems like 2 of the 3 proposed solutions wouldn't work on Heroku. I'd link to these, but new Stackoverflow users are limited to 2 hyperlinks.

I've also come across the following tools:

Just wondering if you have experience with either the multitenant gem or the simple-rails-multi-tenancy gem. Seems like the most straightforward solution would be to simply put a belongs_to on all my models that need to be under an Account, but I'd really like to know what you're using in the real world!

Edit
Report

1 Answer

2

I am about to embark on this venture(implementing multi-tenancy for a small rails app) and while doing research I stumbled on this SO post.

It is surprising that no one mentioned about the great screencast by RyanB on implementing MT using PostgreSQL schemas which is supported by Heroku.

Here is the link to the screencast http://railscasts.com/episodes/389-multitenancy-with-postgresql.

Concept:

In rails app,we can set a search path for pg connection

      connection.schema_search_path = "schema1, schema2, ..."

any subsequent actions will be executed on schema1 if it finds the corresponding table there. Otherwise, it searches for the table in schema2 and so on. To being with your entire app schema including tenant will be in public and usual practice is to make all the tables except tenant empty in public schema.

New Tenant Registration:

Add an after_create function to your Tenant model to create a new schema for the new tenant and create all (load schema.rb) app tables (except Tenant) into this new schema.

User:

when a user visits, subdomain1.myapp.com, find the schema for this subdomain from tenant table and set the connection search path to 'schema1, public' and authenticate the user.

Please note, my intention is just to cover the concept behind the solution. Refer to RyanB's screencast for the actual solution.

answered 2013-02-11T19:41:34.713

Your Answer