ruby on rails - ActiveRecord model with two databases simultaneously -


i have ruby on rails application 2 database backends - postgresql , memsql (a mysql-compatible analytics database).

how can set model persisted both databases simultaneously, such create, update , delete statements executed on both, , select queries executed on postgresql?

in other words - how can maintain 2 database backends identical using same activerecord model?

you can having 2 model classes. cons many when comes composition , complexity. activerecord shares connections saving them in base class:

class memsqlbase < activerecord::base   establish_connection configurations['memsql'][rails.env]   self.abstract_class = true end  class post < applicationrecord   after_save :push_to_memsql!   def push_to_memsql!     memsqlpost.save_or_update!(self.attributes)   end end  class memsqlpost < memsqlbase   self.table_name = :posts   def self.model_name     activemodel::name.new("post")   end end 

the awkward part share code between post , memsqlpost have use modules not share base class.

it may possible circumvent monkeypatching class connection methods:

# class nothing except holding connection pool class memsqlbase < activerecord::base   establish_connection configurations['memsql'][rails.env]   self.abstract_class = true end  module memsqlmonkeypatch   extend activesupport::concern    class_methods     def connection_pool       memsqlbase.connection_pool     end      def retrieve_connection       memsqlbase.retrieve_connection     end      def connected?       memsqlbase.connected?     end      def remove_connection(klass = self)       memsqlbase.remove_connection     end   end end  class post < applicationrecord   after_save :push_to_memsql!   def push_to_memsql!     memsqlpost.save_or_update!(self.attributes)   end end  class post < memsqlbase   include memsqlmonkeypatch   self.table_name = :posts end 

i have not tested though on own.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -