Accessing Session Object from a model

i realize that this goes against the basic idea of the MVC architecture,
but i’ve found myself in a situation where i need to get information
about the current user in a model & i’m not sure how to do it.

Basically, we have a product where each customer has their own profile
with data stored in a separate database. There are some tables in a
common ‘system-wide’ database such as the user, role & permission
tables, but a lot of other stuff has to be divided up into separate DBs
per customer. I realise this isn’t the best way to organise the data but
it’s a requirement of the project so i’m stuck with it.

I need to be able to tell my model what DB to connect to based on what
profile the logged in user has. Something similar to:

[code]
class Report < ActiveRecord::Base
establish_connection({
:adapter => MyConfig.config(:db_adaptor),
:username => MyConfig.config(:db_user_name),
:password => MyConfig.config(:db_password),
:database => @session[:user].profile.name + “_dbname”
})
set_table_name “reports”
.
.
.
end

All the DBs have the same login information so the only thing I need to
change is the :database attribute, but I can’t figure out any way to
pass this information into the model before the connection takes place.
Any help or ideas would be greatly appreciated!

Thanks in advance

Stan

ã?¹ã?¿ã?³ ã??ã?ºã?¬ã??ã?¯ wrote:

Basically, we have a product where each customer has their own profile
with data stored in a separate database. There are some tables in a
common ‘system-wide’ database such as the user, role & permission
tables, but a lot of other stuff has to be divided up into separate DBs
per customer. I realise this isn’t the best way to organise the data but
it’s a requirement of the project so i’m stuck with it.

Try using a before_filter in your controller:

before_filter :establish_per_user_db_connection

def establish_per_user_db_connection
Report.establish_connection(
:adapter => MyConfig.config(:db_adaptor),
:username => MyConfig.config(:db_user_name),
:password => MyConfig.config(:db_password),
:database => @session[:user].profile.name + “_dbname”)
end

Zsombor

ã?¹ã?¿ã?³ ã??ã?ºã?¬ã??ã?¯ wrote:

Well, that works but only if i want to globally switch db’s between users.
The thing is, i need to access a common USER table, and then switch to
separate dbs…

You already different connections for the User and Report models, since
only the last was reset. How exactly does this fail?

Hi. Sorry I missed out the report part of Report.establish_connection.
This stuff might work indeed.

I could solve my problem though using views to the user table/db from
all my profile db’s (all the profiles have the same views to the same
user db), so i just switch to the correct user db on arrival.

Thanks
Stan

Well, that works but only if i want to globally switch db’s between
users.
The thing is, i need to access a common USER table, and then switch to
separate dbs…

Stan