ruby-on-railsshardingoctopus

Rails while iterating through all the shards, get the shard name using Octopus


The setup: I have multiple databases of the same schema. Each database represent the data for different sites. I want to iterate through each of the instances and print out the user count along with the shard name. How can I do that?

This is the code I have so far:

    Octopus.using_all do
      users = User.all
      ap @shard  # This doesn't work
      ap users.length
    end

Solution

  • There is a method in Shard::Proxy which returns shard names, but I can't see an obvious way to retrieve it.

    I think you'd have to iterate through a list of shard names manually.

    %i(shard_1 shard_2 shard_3).each do |shard|
      users = User.using(shard).all
      ap shard 
      ap users.length
    end