Best way to handle multitenancy in Rails 3
Asked Answered
S

3

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.

Sublime answered 23/9, 2010 at 8:34 Comment(0)
S
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
Sublime answered 30/9, 2010 at 14:40 Comment(4)
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?Atkinson
@Atkinson 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 errorPaco
@Paco 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.Atkinson
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 @AtkinsonPaco
H
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
Haemato answered 23/5, 2011 at 13:49 Comment(0)
H
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

Hamby answered 1/12, 2014 at 10:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.