Different database connections in rails based on user parameters

I am refactoring some functions of an inherited php application that uses several databases with the same structure, one per language. When the user login selects its language, and then all of the following connections are made with db for this application using some code:

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

I would like to reorganize the database, but at the moment this is not an option, because other parts of the software should remain in production with the old structure, while the new application is developed, and for some time after its development.

I saw this question , but the question and the gems offered are pretty old, and it seems that they do not work with Rails 3.

What is the best method to achieve this behavior in my new rails 3 application? Is there any other choice that allows me to change the db structure and fit my needs?

The last detail: in the php application, even the login data is stored in separate tables, that is, each db has its own user table, and when the user logs into it, it also passes the language parameter in the login form. I would like to use devus for auth in a new application that probably won't work with this approach, so I'm going to duplicate (I know, this is not DRY) registration information in a separate user model with a language attribute and a separate db used between languages to use development features with my application. Will this cause any problems?

EDIT:

For completeness, I finished 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 configuration in the base model (in fact, this is not entirely true, but this is to make everything clear)

 MyModel < AR::Base establish_connection "production_#{session[:language]}" ... end 
+4
source share
2 answers

use establish_connection in your models:

 MyModel < AR::Base establish_connection "db_appname_#{session[:language]}" ... end 
+4
source

Use the MultiConfig gem that I created to make this easy.

You can specify the configs in a separate file, for example database_italian.yml, etc., and then call:

ActiveRecord::Base.config_file = 'database_italian'

Thus, it will be much easier to maintain and clean. Just add more db configuration files as you wish

0
source

Source: https://habr.com/ru/post/1347085/


All Articles