Skip to content

Instantly share code, notes, and snippets.

@briandoll
Created November 20, 2009 22:50
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save briandoll/239853 to your computer and use it in GitHub Desktop.
Save briandoll/239853 to your computer and use it in GitHub Desktop.
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))
@shawnpyle
Copy link

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.

def self.set_table_name(value = nil, &block)
    value = "#{table_name_prefix}#{value}" if value && !value.match(/^#{table_name_prefix}/)
    define_attr_method :table_name, value, &block
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment