Switch database based on input request


#1

Hi,

is there any solution to switch the database for active_record releated
on request input ?
i try to code an application, where the user can enter the db connect
string for the request in an for.
i don’t konwn all databases, so it’s not possible to write the connect
strings in an file whitch will be readed at startup :frowning:

i need sometime like

def do_something
connection = create_connection( :params )
set_active_record_connection_for_thread( connection )

Person.find_by_sql

connection.close
end

Can anyone help,

André


#2

ActiveRecord classes hold connection info. In your case, you’ll want
something like:

def action_name
Person.establish_connection(connection_params)
Person.find…
end

Of course, there’s a lot of ways you can do this, and you’ll need to
make
sure that connections don’t stay open or don’t run into each other.
Another
note: subclasses of AR::Base share connection information, and any class
down the hierarchy can define it’s own connection params.

Jason


#3

Hi Jason,

i think establish_connection will set the connection as static variable
for all instances of this type. whats goning on, if an concurrent
request calls establish_connection too ?!?

Andre

Jason R. wrote:

ActiveRecord classes hold connection info. In your case, you’ll want
something like:

def action_name
Person.establish_connection(connection_params)
Person.find…
end

Of course, there’s a lot of ways you can do this, and you’ll need to
make
sure that connections don’t stay open or don’t run into each other.
Another
note: subclasses of AR::Base share connection information, and any class
down the hierarchy can define it’s own connection params.

Jason