Created
November 20, 2009 22:50
-
-
Save briandoll/239853 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ActiveRecord::Base | |
def self.table_name_prefix | |
"appname." | |
end | |
end | |
class TransactionalBase < ActiveRecord::Base | |
self.abstract_class = true | |
establish_connection "#{RAILS_ENV}-transactional" | |
def self.table_name_prefix | |
"appname_transactional." | |
end | |
end | |
# Now you can do JOINs across two databases on the same host | |
# provided your permissions are set up appropriately | |
class Hospital < AcitveRecord::Base | |
has_many :hospital_doctors | |
has_many :doctors, :through => :hospital_doctors | |
end | |
class HospitalDoctor < ActiveRecord::Base | |
belongs_to :hospital | |
belongs_to :doctor | |
end | |
class Doctor < TransactionalBase | |
has_many :hospital_doctors | |
has_many :hospitals, :through => :hospital_doctors | |
end | |
Example: | |
> Hospital.first.doctors | |
Will use the following SQL: | |
SELECT `appname_transactional`.`doctors`.* FROM `appname_transactional`.`doctors` INNER JOIN `appname`.`hospital_doctors` ON `appname_transactional`.`doctors`.id = `appname`.`hospital_doctors`.doctor_id WHERE ((`appname`.`hospital_doctors`.hospital_id = 1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you're working with legacy tables and need to set the table name, you may want augment ActiveRecord::Base's set_table_name so that the models that call set_table_name and those that don't get the correct prefix.