3

I use Apartment for multi-tenancy. Is there any way that I can run a query across all tenants instead of just my current one?

One kind of annoying way to do it would be something like

tenants.map do | tenant |
  Apartment::Tenant.switch! tenant
  User.all
end

I'm not sure what the side effects of switching tenants are though, and it would be nice if there was some way to set the tenant at a query level.

Xodarap
  • 11,581
  • 11
  • 56
  • 94
  • 1
    You can always exclude a particular model from being tenant-based - however if you're talking about reporting on multiple tenants, then no, what you have is the way to do it. If you think about it, it's no different then what the application does each time a user connects, it switches the database to their tenant and performs actions, but it could easily be excessive. Depending on what you're trying to accomplish. – trh Apr 12 '16 at 15:37
  • @trh That would make a good answer... – Brad Werth Apr 12 '16 at 15:47
  • @trh: Yep, I know I could exclude it from being tenant-based, but this is something that I usually want to be tenant-based except in certain administrative scenarios. – Xodarap Apr 12 '16 at 15:56
  • can't [persistence schema](https://github.com/influitive/apartment#persistent-schemas) help here? – Arup Rakshit Aug 27 '17 at 04:37

2 Answers2

3

One slightly better way of doing things is

tenants.map do | tenant |
  Apartment::Tenant.switch(tenant) do
    User.all
  end
end

This way it's not changing the current tenant

Xodarap
  • 11,581
  • 11
  • 56
  • 94
1

Another way would be:

Apartment::Tenant.each do
  User.all
end
Pedro Schmitt
  • 150
  • 3
  • 9