Ruby on Rails Friday, March 29, 2013


  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










--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msg/rubyonrails-talk/-/IVc1M8g7z-AJ.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

No comments:

Post a Comment