Search code examples
ruby-on-railsrubysql-serveractiverecordmultiple-databases

ruby - ActiveRecord multiple databases for the same model


We have a vendor-provided application that is using a MSSQL database as backend. We have multiple instances of this application, and thus multiple databases / databases servers hosting the same database model but with different data.

I'm trying to develop a very simple "browsing tool" to provide a single view of all theses databases (read only).

I'm using Sinatra/ActiveRecord/ActiveRecord-SqlServer-Adapter and I have my models overloaded to comply with the database model.

What I'm now looking for is a way to request all the databases at once and aggregate all the results.

Is there any way to do this in vanilla ActiveRecord? Using a gem? I found the db-charmer gem that does something like that, but's it's only compatible with MySQL and I can't get it to work without rails anyway.

Any idea?


Solution

  • I finally found a gem that I was able to hack to do what I need.

    I used Octopus and its sharding capabilities, and I added a simple method to my base controller class (that all my other controllers are based off of) that looks like this:

    
    def on_all_shards(&block)
      Octopus.config[:shards].each.collect do |shard, shard_config|
        Octopus.using(shard) do
          yield
        end
      end
    end
    

    Then in my controllers, whenever I need to aggregate the results of all my shards if just do:

    
    on_all_shards do
      Model.first
    end
    

    In this case, I would get an array of the first record of this Model/table from each database (1 record / database).

    Thank you guys for pointing me to the right direction (ActiveRecord connection/connection_pool management)!