简体   繁体   中英

Best way to handle multitenancy in Rails 3

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM