views:

716

answers:

3

I need 2 db connections in my rails model, is there a not so hackey way to do that?

any links or search keywords would be great :)

+10  A: 

Add new sections to your database.yml e.g.

other_development:
  adapter: mysql
  database: otherdb_development
  username: root
  password:
  host: localhost

other_production:
  adapter: mysql
  database: otherdb_production
  username: root
  password:
  host: localhost

and then for each model which isn't in the default database add an establish_connection line:

class MyModel < ActiveRecord::Base
  establish_connection "other_#{RAILS_ENV}"
end
mikej
awesome thanks :)
gustavgans
+2  A: 

mikej is right. I did however write a gem that makes the model code to connect a little bit cleaner, check it out.

railsninja
Above link is broken. Here's the correct one: http://github.com/cherring/connection_ninja
abeger
Thanks for the correction :)
railsninja
A: 

I have been using the following to connect to 2 db in the same app. I put them in lib folder since everything in there is loaded.

require 'active_record'

class OldDatabase < ActiveRecord::Base
  self.abstract_class = true
  establish_connection(
  :adapter  => 'mysql',
  :database => 'weather',
  :host     => 'localhost',
  :username => 'root',
  :password => 'password'
  )
end

class NewDatabase < ActiveRecord::Base
  self.abstract_class = true
  establish_connection(
  :adapter  => 'mysql',
  :database => 'redmine',
  :host     => 'localhost',
  :username => 'root',
  :password => 'password'
  )
end

class WeatherData < OldDatabase
end

class Board < NewDatabase
end

Hope that helps

penger