Created
November 28, 2011 19:12
-
-
Save stackdump/1401589 to your computer and use it in GitHub Desktop.
Method of using multiple db connection in ActiveRecord
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
# The idea here is to specify that a given model should use another | |
# database without having to change the entire inheritance hierarchy | |
# declare model for table in primary connection | |
class Bar < ActiveRecord::Base | |
# assume we have logic here that we don't want to refactor into a module | |
# but we do want to inherit in OtherDb::Bar | |
end | |
module Foo | |
# base model in Foo namespace - uses another db | |
class BaseConnection < ActiveRecord::Base | |
# OtherDb::Title.database contains a db config hash | |
# This would probably go in the initializers | |
establish_connection OtherDb::Title.database | |
end | |
# module used to override db connection | |
module OtherDb::Base | |
def retrieve_connection | |
# connection_handler.retrieve_connection(self) # normal behavior | |
connection_handler.retrieve_connection(Foo::BaseConnection) # use db from Foo::BaseConnection | |
end | |
end | |
# Foo::Bar is identical to ::Bar but is in another db | |
class Bar < ::Bar | |
extend OtherDb::Base | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment