Belorion wrote:> This is a question regarding ActiveRecord outside of Rails.
>
> I have several databases that have absolutely identical table structure.
> I
> have a
>
> ActiveRecord::Base.establish_connection(
> :adapter => "mysql",
> :host => "localhost",
> :username => "user",
> :password => "password",
> :database => "db"
> )
>
> At the beginning of my script. Is there an easy way to switch between
> different databases? I.e. without closing the connection to the old, and
> opening on the new? I''m switching back and forth between them
quite
> frequently and don''t want to have to re-establish a connect to
MySQL
> every
> time.
>
> Matt
Matt,
I did this inside of a Rails structure, but hopefully you get the idea.
--script/dbtest---
#!/usr/bin/env ruby
require File.dirname(__FILE__) + ''/../config/boot''
db_config = YAML::load(File.open("#{RAILS_ROOT}/config/database.yml"))
dev_connection =
ActiveRecord::Base.mysql_connection(db_config["development"])
test_connection =
ActiveRecord::Base.mysql_connection(db_config["test"])
prod_connection =
ActiveRecord::Base.mysql_connection(db_config["production"])
puts ''dev conn active?: '' + dev_connection.active?.to_s
puts ''test conn active?: '' + test_connection.active?.to_s
puts ''prod conn active?: '' + prod_connection.active?.to_s
puts ''Switch to dev db:''
Foo.connection=dev_connection
puts Foo.find_all[0].value
Foo.clear_connection_cache!
puts ''Switch to test db:''
Foo.connection=test_connection
puts Foo.find_all[0].value
Foo.clear_connection_cache!
puts ''Switch to prod db:''
Foo.connection=prod_connection
puts Foo.find_all[0].value
Foo.clear_connection_cache!
puts ''dev conn active?: '' + dev_connection.active?.to_s
puts ''test conn active?: '' + test_connection.active?.to_s
puts ''prod conn active?: '' + prod_connection.active?.to_s
--app/models/foo.rb--
class Foo < ActiveRecord::Base
def self.table_name() "foo" end
end
--db/development_structure.sql--
CREATE TABLE `foo` (
`value` varchar(10) default NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--a script run--
./script/dbtest
dev conn active?: true
test conn active?: true
prod conn active?: true
Switch to dev db:
dev
Switch to test db:
test
Switch to prod db:
prod
dev conn active?: true
test conn active?: true
prod conn active?: true
--
-damon
http://damonclinkscales.com/
--
Posted via http://www.ruby-forum.com/.