2017-05-18 5 views
1

私はRails5を実行しており、サブドメインに基づいてDBを変更したいアプリケーションを持っています...これを使用していますquestion/answer(これはRails 3に基づいています)そのような作品を作りましょう。カスタム接続ハンドラを使用するようにベースモデルを変更しましたが、すべてのリクエストではなく、サーバーの起動時にのみ実行されます。ここでRails:リクエストでDB接続を接続する

私のベースモデル&カスタム接続ハンドラです:

class CustomConnectionHandler < ActiveRecord::ConnectionAdapters::ConnectionHandler 
    def initialize 
    super 
    @pools_by_subdomain = {} 
    end 

    # Override the behaviour of ActiveRecord's ConnectionHandler to return a 
    # connection pool for the current domain. 
    def retrieve_connection_pool(krass) 
    # Get current subdomain somehow (Maybe store it in a class variable on 
    # each request or whatever) 
    # if (defined?(@@request)).nil? 
    # return 
    # end 
    # 
    # if @@request.host == 'localhost' 
    # return 
    # end 
    # if @@request.subdomain.present? #&& request.subdomain != "www" 
    # hard code domain for now, i have a database setup called new_site 
     subdomain = 'new_site'#@@request.subdomain 
    # end 
    @pools_by_subdomain[subdomain] ||= create_pool(subdomain) 

    end 

    private 
    def create_pool(subdomain) 
    conf = Rails.configuration.database_configuration[Rails.env].dup 
    #conf = ActiveRecord::Base.connection.instance_variable_get("@config").dup 
    # The name of the DB for that subdomain... 
    conf.update(:database => subdomain) 
    #resolver = ConnectionSpecification::Resolver.new(conf, nil) 
    # Call ConnectionHandler#establish_connection, which receives a key 
    # (in this case the subdomain) for the new connection pool 
    ApplicationRecord.establish_connection(conf) 
    end 
end 

class ApplicationRecord < ActiveRecord::Base 
    self.abstract_class = true 
    self.connection_handler = CustomConnectionHandler.new 
end 

は、あなたがコメントしたコードの一部で見ることができるように、私の意図は、リクエストのサブドメインに基づいて、プールを切り替えることができるようにすることです(別のクライアント)...しかし、私のベースモデルは、最初の要求でのみ実行され、再び決して実行されません。他のすべてのモデルは、ApplicationRecordをベースとして使用しています...私はここで何をすべきか分かりません。誰も私の目標を達成するのを助けることができますか?

答えて

0

これを見つけた人にとって、私はシャーディングを通じて何をしたいのかを達成することができました。私はOctopusシャード宝石をインストールし、ドキュメントのようにshards.ymlをセットアップしました。次に、このコードをアプリケーションコントローラに追加しました:

around_filter :select_shard 

def select_shard(&block) 
    # changes shard based on subdomain of host. 
    # if none found, it will use the default shard 
    shard = 'default'.to_sym 
    if request.subdomain.present? 
    shard = request.subdomain.to_sym 
    end 
    Octopus.using(shard, &block) 
end 

すべての設定、シンプルで機能的です!

関連する問題