Tuesday, March 8, 2011

Multiple Database Connection in Ruby on Rails

Ruby on Rails sets up the connection depending on your application’s database.yml file. In database.yml file you set up configration environmentwise.

As I active record allow to access single database but you want to access more than one databases than it required to have multiple connection at a time. Now you think that how this possible. So Rails provides gem to implement you need. Follow the below steps:

1. Install gem
sudo gem install magic_multi_connections

2. After installing gem there is one patch required in connected.rb(/usr/lib/ruby/gems/1.8/gems/magic_multi_connections-1.2.1/lib/magic_multi_connections/connected.rb)

raise ( "uninitialized constant # (const_id)") unless

return unless target_class

3. Now edit the config/database.yml file to create some more databases:


adapter: mysql
encoding: utf8
database: app_development
username: tester
password: testerpwd
host: localhost


adapter: mysql
encoding: utf8
database: appx_development
username: tester
password: testerpwd
host: localhost

Default in rails main application database has read-write permission , and the other databases than you default application database have read-only pemission.

4. Now in environment.rb ,you have to add end of environment.rb:

require 'magic_multi_connections'
connection_names = do |name|
name =~ /^#{ENV['RAILS_ENV']}_clone/

@@connection_pool = do |connection_name|
Object.class_eval <<-EOS
module #{connection_name.camelize}
establish_connection :#{connection_name}


5. Next, you create same clone for databases which you have access by following below steps.

cp config/environments/development.rb config/environments/development_clonex.rb

6. Now, You want to migrate the new databaseclone than only follow below step.

rake db:migrate RAILS_ENV=development_clonex

7. Lets check whether multiple pool created or not and we are able to access data from different database or not through console.
$ ruby script/console

· Check for connection pool

>> @@connection_pool
=> [DevelopmentClonex]

As we create clonex than it listed here. If you create more than one then you have array with multiple clone.

Now access table from other database by
>> DevelopmentClonex::Model_name.model_methods

Example: @users = DevelopmentClonex::User.find(:all)
puts'qadexnsdev', @users.size ##It access database 1
@uses = User.find(:all)
puts'qadex_test', @uses.size ##It access database 2
Now use other features of multi_magic_connection.

Hope this article will help you. If you have any suggestion or query than just leave comment here.
Sathis is Ruby on rails Project Lead in chennai,4 + years experience in ror.

No comments:

Post a Comment