开发者

Best way to handle multitenancy in Rails 3

开发者 https://www.devze.com 2023-01-17 02:00 出处:网络
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.

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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消