4

I'm refactoring some features of a legacy php application which uses multiple databases with the same structure, one per language. When an user login choose his language and then all the following connections are made with the db for that app with some code like this:

$db_name = 'db_appname_' . $_SESSION['language'];
mysql_connect(...);
mysql_select_db($db_name);

I'd like to refactor also the database, but currently it's not an option because other pieces of software should remain in production with the old structure while the new app is developed, and for some time after it's been developed.

I saw this question, but both the question and the suggested gems are pretty old and it seems that they are not working with Rails 3.

Which is the best method to achieve this behavior in my new rails 3 app? Is there any other choice that avoid me to alter the db structure and fits my needs?

Last detail: in the php app even the login information are kept in separate tables, i.e. every db has its own users table and when the user logs in it also passes a language param in the login form. I'd like to use devise for auth in the new app which likely won't work with this approach, so I'm thinking to duplicate (I know, this is not DRY) login information in a separate User model with a language attribute and a separate db shared among languages to use devise features with my app. Will this cause any issue?

EDIT:

For completeness, I ended with this yml configuration file

production: &production
  adapter: mysql
  host: localhost
  username: user
  password: secret
  timeout: 5000

production_italian:
  <<: *production
  database: db_app_ita

production_english:
  <<: *production
  database: db_app_eng

and with this config in base model (actually not exactly this but this is for keeping things clear)

MyModel < AR::Base
  establish_connection "production_#{session[:language]}"
  ...
end
Community
  • 1
  • 1
Fabio
  • 18,856
  • 9
  • 82
  • 114

2 Answers2

4

use establish_connection in your models:

MyModel < AR::Base
  establish_connection "db_appname_#{session[:language]}"
  ...
end
fl00r
  • 82,987
  • 33
  • 217
  • 237
  • I see [here](http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-establish_connection) that this method require an hash as argument, so I should give the name of a connection in database.yml or :database => "db_appname_#{session[:language]}"? Thanks for the hint, I'll experiment it. – Fabio Apr 07 '11 at 18:02
  • yep, you're right. You should store all your connections in `database.yml` file. That's how Rails do – fl00r Apr 07 '11 at 18:04
0

Use MultiConfig gem I created to make this easy.

You could specify the configs in separate file like database_italian.yml etc and then call:

ActiveRecord::Base.config_file = 'database_italian'

This way it will be much easier to maintain and cleaner looking. Just add more language db config files as you wish

ShadyKiller
  • 700
  • 8
  • 16