Step1> Open your database.yml file. Under the three standard databases (development, test and production) add the informations needed to connect to you extra dataabse(consider u are running application in production mode and have student_database and second database has mail_database) . Use the standard yml sintax like:
development:
adapter: mysql
database: Login_app_development
username: root
password:
host: localhost
adapter: mysql
database: Login_app_development
username: root
password:
host: localhost
test:
adapter: mysql
database: Login_app_test
username: root
password:
host: localhost
adapter: mysql
database: Login_app_test
username: root
password:
host: localhost
production:
adapter: mysql
database: student_database
username: root
password:
host: localhost
adapter: mysql
database: student_database
username: root
password:
host: localhost
mail:
adapter: mysql
database: mail_database
username: root
password:
host: localhost
adapter: mysql
database: mail_database
username: root
password:
host: localhost
Step2> I am considering that you have model for student database (ex: student) Create model for mail database using command prompt
ruby script/generate model mail
Step3> You need to manually overwrite the estabilish_connection method for the models linked to the external database(mail_database). Doing this execute these lines where u want to switch database to mail_database
dbconn = YAML.load(File.join(RAILS_ROOT, “config/database.yml”),”r”))["mail"]
Mail.establish_connection(dbconn)
After executing these lines all model will connect to mail_database if u want to shift back to student_database then execute these lines
dbconn = YAML.load(File.join(RAILS_ROOT, “config/database.yml”),”r”))[ENV['RAILS_ENV']]
Student.establish_connection(dbconn)
Using before_filter you can switch databases by executing above lines