在Rails中实现多租户

4
我们有一个中等规模的应用程序,部署在多个客户的在线 VPS 服务器上。代码对于所有客户端都相同。维护变得非常繁重。即使是同样的更改,我们也必须在这么多服务器上部署。因此,我们计划为我们的应用程序实现多租户功能。
我们发现了一些宝石,但它们不能满足我们的需求,因此我们计划进行实施。
我们创建了一个新模型 "Client" 并创建了一个抽象超类,该超类从 "ActiveRecord::Base" 继承,并且所有依赖类都继承自该类。现在的问题是当我想要从我的超类添加 "default_scope" 时。
class SuperClass < ActiveRecord::Base
  self.abstract_class = true
  default_scope where(:client_id => ???)
end 

每个用户的 ??? 都不同。因此我无法给出静态值。但我不确定如何动态设置这个范围。那么该怎么办?


这不是回答问题的问题,但是你有考虑过使用Capistrano在多台服务器上部署吗?这可能会解决您的维护问题,而无需进行任何代码更改。 - Chris Heald
@ChrisHeald 这不仅仅是部署问题。我们有多个问题,所以我们想要转向多租户。 - Rahul
1个回答

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过滤器,根据子域名设置当前客户端。
class ApplicationController < ActionController::Base
  before_filter :set_current_client

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接