One connection per session

Hi all,

I'm new to rails and started building an application on top of my
legacy database. I trying to get a login/out system work and I'm using
login generator as a basis. My problem is: The user that logs in to the
app must also connect to the database (with his own username/password).
This means that I need to have a connection per session. Does anyone
have some hint on how to do this without needing to reconnect for each
request?

Regards,

Håkon

I'm not sure I understand you correctly. Can I store the connection in
the session? I thought I needed to do a
ActiveRecord::Base.establish_connection per session if each user should
have their own connection to the database.

Håkon

I think you will have to reconnect the user to the database for each
controller action he invokes.
First insert users database info into config/database.yml file. Then
store the name of the database into session when a user logs in. Then
in the application controller do:

    before_filter :db_connect
  private
    def db_connect
      if session['database']
        ActiveRecord::Base.establish_connection(session['database'])
      end
    end

and in your login controller:

  def your_login_method
    # figure out database name
    # ...
    if authenticate(login, password)
      session['database'] = database_name
      redirect_to :somewhere
    end
  end