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
As the author of the multitenant gem, I'm obviously biased, but I really believe that it is a great solution! The goal of the gem is to simplify this common application need and make it trivial to implement.
The "old school" alternative is to use rails object chaining to ensure that all queries are done through the associated parent. The issue with this approach is that your Tenant object becomes a dumping ground for has_many associations.
class Tenant
has_many :users
end
# query for users in the current tenant
current_tenant.users.find params[:id]
The multitenant gem solves this by ensuring that all queries generated are automatically aware of the current tenant. And it also ensures that new records are created and automatically assigned to the current tenant so you don't need to add any special before_save callbacks.
ex:
Multitenant.with_tenant current_tenant do
# queries within this block are automatically
# scoped to the current tenant
User.all
# records created within this block are
# automatically assigned to the current tenant
User.create :name => 'Bob'
end