Rah*_*hul 4 ruby ruby-on-rails multi-tenant
我们在各自的在线VPS服务器上为多个客户端部署了中型应用程序.所有客户端的代码都相同.维护正成为一个巨大的负担.即使是同样的变化,我们也会在如此众多的服务器中部署.因此,我们计划为我们的应用程序实现多租户功能.
我们遇到了一些宝石,但这并没有达到目的,因此我们计划实施它.
我们创建了一个新模型Client
,我们创建了一个abstract superclass
继承自的模型ActiveRecord::Base
,所有依赖类都继承了这个类.现在,当我想default_scope
从我的超类中添加时,问题就来了.
class SuperClass < ActiveRecord::Base
self.abstract_class = true
default_scope where(:client_id => ???)
end
Run Code Online (Sandbox Code Playgroud)
??? 每个用户的变化.所以我不能给出静态价值.但我不确定如何动态设置此范围.那可以做些什么呢?
我们执行以下操作(您可能不需要线程安全部分):
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
Run Code Online (Sandbox Code Playgroud)
然后在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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
828 次 |
最近记录: |