5

I'm building multi-tenant application.

All data isolation is done by TenantID column in each table.

What is the best way to automatically handle multi-tenancy for all tenant models.

Example:

Contacts.new({.....}) should automatically add :tenant => curret_user.tenant
Contacts.where({....}) should also add :tenant => curret_user.tenant

Currently I see something like this in CanCan gem which that can fetch records for specific user parameters. But it is not providing anything for insert and update operation. Or may be I doesn't understand how to do it.

Regards, Alexey Zakharov.

shingara
  • 46,608
  • 11
  • 99
  • 105
Alexey Zakharov
  • 24,694
  • 42
  • 126
  • 197

3 Answers3

1

I Used Act As Tenant gem for multitenancy . It's pretty good gem and very easy to use. Here is a documentation of this gem Act As Tenant

1

It is possible if you will work with all collections through tenant object.

Here is sample using Mongoid:

#Find all products with price > 500 in current tenant scope

current_tenant.products.where(:price.gt => 500) 

#It also work for create and save operations

current_tenant.products.create :name => "apple", :price => 200
Alexey Zakharov
  • 24,694
  • 42
  • 126
  • 197
  • Did you use the multitenant gem to accomplish this? I'm trying to figure out how to assign a new tenant object during registration with devise. Can you help? – Nathan Apr 02 '12 at 03:33
  • @Nathan did you manage to solve your issue? I'm facing the same issue on login, because the current_tenant is not set at this point and yields invalid credentials error – scanales Mar 05 '13 at 21:04
  • 1
    @scanales I ended up scoping each of my queries to the current_tenant. There are gems out there that will do model level call backs, so it really depends on what you're trying to accomplish. – Nathan Mar 12 '13 at 22:00
  • I found out it was just a matter of calling `scope_current_tenant` at the very top of `ApplicationController` so that it was properly set before every other callback @Nathan – scanales Mar 13 '13 at 22:48
1

I'd recommend checking out the multitenant ruby gem. It makes it trivial to ensure that all queries performed respect the current tenant. http://blog.codecrate.com/2011/03/multitenant-locking-down-your-app-and.html

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
ryan
  • 81
  • 2