Auto switching databases from a rails app gracefully from the ApplicationController?

Posted by Zaqintosh on Stack Overflow See other posts from Stack Overflow or by Zaqintosh
Published on 2010-03-24T18:17:38Z Indexed on 2010/03/24 22:33 UTC
Read the original article Hit count: 471

I've seen this post a few times, but haven't really found the answer to this specific question.

I'd like to run a rails application that based on the detected request.host (imagine I have two subdomains points to the same rails app and server ip address: myapp1.domain.com and myapp2.domain.com).

I'm trying to have myapp1 use the default "production" database, and myapp2 requests always use the alternative remote database. Here is an example of what I tried to do in Application controller that did not work:

class ApplicationController < ActionController::Base
  helper :all 
  before_filter :use_alternate_db

  private

    def use_alternate_db

      if  request.host == 'myapp1.domain.com'
        regular_db
      elsif request.host == 'myapp2.domain.com'
        alternate_db
      end

    end

    def regular_db
      ActiveRecord::Base.establish_connection :production
    end

    def alternate_db
      ActiveRecord::Base.establish_connection(
      :adapter => 'mysql',
      :host => '...',
      :username => '...',
      :password => '...',
      :database => 'alternatedb'
      )

    end
end

The problem is when it switches databases using this method, all connections (including valid sessions across the different subdomains get interrupted...). All examples online have people controlling database connectivity at the model level, but this would involve adding code all over my application. Is there some way to globally switch database connections on a per-request basis in the manner I'm suggesting above WITHOUT having to inject code all over my application?

The added complexity here is I'm using Heroku as a hosting provider, so I have no control at the apache / rails application server level.

I have looked at solutions like dbcharmer and magicmodels, but none seem to show examples of doing it in the manner that I'm trying to. Thanks for any help!

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about rails