使用子域并且没有子域的多租户Ruby应用程序

时间:2012-12-06 14:30:03

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

我开发了一个使用PostgreSQL和多模式的应用程序来实现应用程序的多租户方面。租户通过子域名进行检查,但我正在尝试找到一种方法,以便仍然可以使用主域名作为我自己的注册点和管理后端。

下面是我的应用程序控制器,我相信支票租户正在发生。

我从这里http://railscasts.com/episodes/389-multitenancy-with-postgresql?view=comments

跟踪了railscast
class ApplicationController < ActionController::Base


protect_from_forgery

  rescue_from CanCan::AccessDenied do |exception|
    redirect_to root_path, :alert => exception.message
  end

  before_filter :mailer_set_url_options

  def mailer_set_url_options
    ActionMailer::Base.default_url_options[:host] = request.host_with_port
  end

  around_filter :scope_current_tenant

private

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end
 helper_method :current_user

  def current_tenant
    @current_tenant ||= Tenant.find_by_subdomain!(request.subdomain)
  end
  helper_method :current_tenant

  def scope_current_tenant(&block)
    current_tenant.scope_schema("public", &block)
  end
end

我注意到的另一个问题是通过设计。它似乎是因为多租户并且在应用程序控制器中定义帮助程序current_user对于来自设计的会话,任何想法都很挑剔?

2 个答案:

答案 0 :(得分:1)

如果您的主域没有租户(例如访问者),因此在这种情况下current_tenant设置为nil,您不能调用current_tenant.scope_schema,但我相信您可以这样做:

 def current_tenant
   # Select tenant based on a user and set it to nil if no user:
   @current_tenant ||= current_user.tenant unless current_user.nil?
 end
 helper_method :current_tenant

 def scope_current_tenant(&block)
   if current_tenant.nil?
      scope_visitor_schema
      yield
   else
     current_tenant.scope_schema("public", &block)
   end
 end  

 def scope_visitor_schema()
   original_search_path = ActiveRecord::Base.connection.schema_search_path
   ActiveRecord::Base.connection.schema_search_path  = 'public'
 ensure
   ActiveRecord::Base.connection.schema_search_path = original_search_path
 end

在此示例中,根据用户而不是子域选择租户,但方法是相同的。

答案 1 :(得分:0)

我找到了一个解决方案并忘了发帖,但你的评论让我记住了。这是我在确定当前客户端范围时所做的事情:

基本上,当子域名等于current_id时,我将"admin"某些内容设为无效,在本例中为"admin",并且当子域名为{时,请勿设置current_id {1}}或空白(我将用于主页。

希望这有帮助

www