Active Record with 2 databases
Forrest To use active record with another database, simply create a new model and name it whatever you would like. For example, If your current Rails App is set up to use the database example_development, and you need table customers from another database, create a new model and name it other_customer.rb like so;
class OtherCustomer< ActiveRecord::Base
set_table_name "customers"
OtherCustomer.establish_connection(
:adapter => “mysql”,
:host => “localhost”,
:username => “root”,
:password => “”,
:database => “other_db_development”
)
end
The tricky thing here is if there happens to be a table already named customers in your current Application, it will start using this new configuration for any call of Customer. The trick to this is to add the same establish connection in your current Customer model. So that customer.rb now reads;
class Customer< ActiveRecord::Base
Customer.establish_connection(
:adapter => “mysql”,
:host => “localhost”,
:username => “root”,
:password => “”,
:database => “example_development”
)
end
There, now any call of Customer or Customer.* will pull from example_development whereas any call of OtherCustomer or OtherCustomer.* will pull from other_db_development. Any other model will continue to query example_development.
Posted in ruby on rails |