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, ther
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.