Blog is moved http://imnithin.github.io/multiple-database.html
Multiple DB connections using ActiveRecord, dynamically.
Connection to multiple database in easy and efficient and dynamic way..
database.yml
development:
adapter: mysql2
encoding: utf8
reconnect: true
database: [DB name]
pool: 5
username: [your username]
password: [your password]
host: [host name]
external:
adapter: mysql2
encoding: utf8
reconnect: true
database: [DB name]
pool: 5
username: [your username]
password: [your password]
host: [host name]
create a class in your model and inherit from ActiveRecord
Class ExternalDatabaseConnection< ActiveRecord::Base
self.abstract_class = true
establish_connection(:external)
attr_protected # used to permit table related attributes, so you don't need to worry about attr_accessible
end
self.abstract_class = true This tells ActiveRecord that it shouldn’t look for a table to go with that class. Setting it, depends on the information available on database.
Setting table name and usage
ExternalDatabaseConnection.table_name = "payments"
ExternalDatabaseConnection.column_names => ["id", "customer_id", "patent_id", "amount", "currency", "date"]
ExternalDatabaseConnection.table_name = "users"
ExternalDatabaseConnection.column_names => ["id", "customer_id", "patent_id", "amount", "currency", "date"]
There is a problem here .. The second table also shows same column information of first.
The fix
ExternalDatabaseConnection.reset_column_information
To override the previous table set, reset_column_information method on the model must be called before setting new table.
Http methods
Set the table and make normal interaction
ExternalDatabaseConnection.reset_column_information
ExternalDatabaseConnection.table_name = "users"
ExternalDatabaseConnection.create(name: 'nithin', phone: 12345678)
rec = ExternalDatabaseConnection.find(id)
rec.update_attributes(name: 'nithin k')
rec.destroy