Forum: Ruby on Rails One connection per session

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
F40111e470717493258257ef61639d29?d=identicon&s=25 HÃ¥kon (Guest)
on 2007-01-09 09:57
(Received via mailing list)
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


Ce953bec3af375ddc75e375233112b28?d=identicon&s=25 harper (Guest)
on 2007-01-09 13:19
put this in controllers/application.rb

        before_filter :set_current_user

  def set_current_user
   User.current_user = session['user']

in the user model add this single line:

        cattr_accessor :current_user

...that should do the trick.

F40111e470717493258257ef61639d29?d=identicon&s=25 HÃ¥kon (Guest)
on 2007-01-10 16:02
(Received via mailing list)
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.

15824f90bc5965a827abb340523a2519?d=identicon&s=25 crzivn (Guest)
on 2007-01-10 19:44
(Received via mailing list)
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
    def db_connect
      if session['database']

and in your login controller:

  def your_login_method
    # figure out database name
    # ...
    if authenticate(login, password)
      session['database'] = database_name
      redirect_to :somewhere
This topic is locked and can not be replied to.