Best way to handle multitenancy in Rails 3

折月煮酒 提交于 2019-12-30 05:04:31

问题


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.


回答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



回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/3776593/best-way-to-handle-multitenancy-in-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!