【问题标题】:Implementing multi tenancy in rails在 Rails 中实现多租户
【发布时间】:2012-10-14 06:36:17
【问题描述】:

我们在各自的在线 VPS 服务器上为多个客户端部署了一个中等规模的应用程序。所有客户端的代码都是相同的。维护正在成为一个巨大的负担。即使是相同的更改,我们也部署在这么多服务器中。所以我们计划为我们的应用程序实现多租户功能。

我们遇到了一些宝石,但这并没有达到目的,因此我们计划实施它。

我们创建了一个新模型Client,我们创建了一个继承自ActiveRecord::Baseabstract superclass,并且所有依赖类都继承了这个类。现在,当我想从我的超类中添加default_scope 时,问题就来了。

class SuperClass < ActiveRecord::Base
  self.abstract_class = true
  default_scope where(:client_id => ???)
end 

???每个用户的变化。所以我不能给出静态值。但我不确定如何动态设置此范围。那么可以做些什么呢?

【问题讨论】:

  • 这并不能回答问题,但是您是否考虑过使用 Capistrano 跨多个服务器进行部署?这可以解决您的维护问题,而无需任何代码更改。
  • @ChrisHeald 这不仅仅是部署。 V 有多个问题,所以我们想转向多租户。

标签: ruby-on-rails ruby multi-tenant


【解决方案1】:

我们执行以下操作(您可能不需要线程安全部分):

class Client < ActiveRecord::Base
  def self.current
    Thread.current['current_client']
  end

  def self.current=(client)
    Thread.current['current_client'] = client
  end
end

class SuperClass < ActiveRecord::Base
  self.abstract_class = true
  # Note that the default scope has to be in a lambda or block. That means it's eval'd during each request.
  # Otherwise it would be eval'd at load time and wouldn't work as expected.
  default_scope { Client.current ? where(:client_id => Client.current.id ) : nil }
end

然后在ApplicationController中,我们添加一个前置过滤器来根据子域设置当前Client:

class ApplicationController < ActionController::Base
  before_filter :set_current_client

  def set_current_client
    Client.current = Client.find_by_subdomain(request.subdomain)
  end
end

【讨论】:

    猜你喜欢
    • 2018-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    • 2018-09-03
    相关资源
    最近更新 更多