Shiva Bhusal
Shiva's Blog

Follow

Shiva's Blog

Follow

Rails | Apartment gem | Resets AR objects when tenant switched

Shiva Bhusal's photo
Shiva Bhusal
·Dec 5, 2018·

1 min read

Play this article

Apartment

Apartment provides tools to help you deal with multiple tenants in your Rails application. If you need to have certain data sequestered based on account or company, but still allow some data to exist in a common tenant, Apartment can help.

Problem

I ran into a weird situation today. Active Record objects stored in vars are removed when I switched from one tenant to another on the fly. This will create a weird test-failing scenario and you never know why its happening.

def switch(name)
  yield(name)
end

@customers = [1,2,3]
switch('shiva') do |name|
  puts name
  puts @customers
end

# Gives output
# shiva
# 1
# 2
# 3

 

but when I do this

@roles = Role.all
@customers = org.branches
@list = [1, 2]

puts 'Role count' + @roles.count.to_s
puts 'Customer count' + @customers.count.to_s
puts 'list count' + @list.count.to_s

Apartment::Tenant.switch!(org.database_name)
puts '-------'
puts 'Role count' + @roles.count.to_s
puts 'Customer count' + @customers.count.to_s
puts 'list count' + @list.count.to_s

output is

Role count2
Customer count2
list count2
-------
Role count0
Customer count0
list count2

 

Reason

# apartment-2.2.0/lib/apartment/adapters/abstract_adapter.rb
# Switch to a new tenant
#
# @param {String} tenant name
#
def switch!(tenant = nil)
  run_callbacks :switch do
    return reset if tenant.nil?

    connect_to_new(tenant).tap do
      Apartment.connection.clear_query_cache
    end
  end
end
 
Share this