connecting to multiple databases in rails

    When strting my application I have three text boxes Username,
password and company name
A user on providing all these goes to user controller login_process
action..That means in my application database.yml have no relevance .It
is as
def login_process
          :adapter => 'postgresql',
          :host => '',
          :username => 'postgres',
          :password => 'password',
          :database => 'gatekeeper'
@the_site = Site.find_by_site_code(params[:company][:whichCompany])

#This sites table contains information of to which different databases
to connect,the adapter using,IPaddress of database server etc based on

                :adapter => @the_site.db_adapter,
                :host => @the_site.db_host,
                :username => @the_site.db_user,
                :password => @the_site.db_pw,
                :database => @the_site.db_name
     -----code continues
      So what I am doing is suppose a user say user1 with password pass1
and gives company1 then it first connects to gatekeeper database and
from that based on site code gets adapter,host,db_user,db_pw and db_name
information and reconnected to that db as above...And I could
successfully do it
        Now my problem is suppose a second user say user2 with passord
pass2 and company company2 connects to the server what happens is now
the already logined first user's (user1) database connection information
changes to that of second That is the last login users information..
        I think I can make you understand the problem..Please help..Why
this happens..How to solve this?

Thanks in advance

Create a seperate rails application for handling the login /
gatekeeper interaction. On successful login, pass the details of the
database connection to another rails application and store these
values in the session of the second application and use it to
establish connections.

For security, get the session id of the user upon successful login
from the first application and pass that on to the secondary
application. You could use a table in the gatekeeper database to
store the session information without worrying about cookies. This
needs more analysis though.

You could maintain a lookup hash in your session with the user_id and
the db_connect parameters and do a connect / disconnect before a DB
operation which is a nightmare for performance. I will be interested
to know about alternative approaches.