在rails中实现多租户

时间:2012-10-13 20:06:40

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

我们在各自的在线VPS服务器上为多个客户端部署了中型应用程序。所有客户端的代码都相同。维护正成为一个巨大的负担。即使是同样的变化,我们也会在如此众多的服务器中部署。因此,我们计划为我们的应用程序实现多租户功能。

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

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

default_scope

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

1 个答案:

答案 0 :(得分:5)

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

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中,我们添加一个before过滤器,根据子域设置当前Client:

class ApplicationController < ActionController::Base
  before_filter :set_current_client

  def set_current_client
    Client.current = Client.find_by_subdomain(request.subdomain)
  end
end
相关问题