Active Record multiple databases with same table schemas

31 views
Skip to first unread message

Jedrin

unread,
Mar 29, 2013, 11:36:53 AM3/29/13
to rubyonra...@googlegroups.com

  We probably need to have a sinatra web server where different clients through different sessions each have different databases but with the same tables.
If I have an active record class such as MyFoo, it would be ideal for it to be for table foo on either db1, db2, etc. If I have MyFoo1 and MyFoo2, I can set
MyFoo as a constant to each of those ie MyFoo = MyFoo2 (MyFoo on database 2), but every time I am in a new session I have to delete the old constant
and set it to the new one. I am not sure that is the only way. I guess I could somehow write a class MyFoo that uses method_missing and then figures out the correct active record instance, but not sure if there was an easier way ?

my test program:

=====================

require  "rubygems"
require  "active_record"
require 'sqljdbc4.jar'


ActiveRecord::Base.configurations["mtmdb"]  = {:adapter         =>  "jdbc",
    :url=> 'jdbc:sqlserver://10.93.31.331;databaseName=mt',
        :username      =>  "",
        :password      =>  "",
    :driver => "com.microsoft.sqlserver.jdbc.SQLServerDriver",
        :autocommit  =>  true}

ActiveRecord::Base.configurations["test"]  = {
:adapter         =>  "jdbc",
    :url=> 'jdbc:sqlserver://10.94.11.11;databaseName=LJ',
        :username      =>  "",
        :password      =>  "",
    :driver => "com.microsoft.sqlserver.jdbc.SQLServerDriver",
        :autocommit  =>  true
}


class TestdbBase1 < ActiveRecord::Base
  self.abstract_class = true
  def self.connect2db
    establish_connection 'test'
  end
end   

class TestdbBase2 < ActiveRecord::Base
  self.abstract_class = true
  def self.connect2db
    establish_connection 'mtmdb'
  end
end   



class MyTestTable1 < TestdbBase1
  self.table_name = "my_test_table"
end   

class MyTestTable2 < TestdbBase2
  self.table_name = "my_test_table"
end   

TestdbBase1.connect2db
MyTestTable = MyTestTable1

rec = MyTestTable.first
p rec

Object.send(:remove_const, :MyTestTable)

TestdbBase2.connect2db
MyTestTable = MyTestTable2

rec = MyTestTable.first
p rec










Reply all
Reply to author
Forward
0 new messages