Rails | Apartment gem | Resets AR objects when tenant switched

1 Min. Read
Dec 5, 2018

 Problem Rails Ruby JS Apartment Multi Tenancy PG Postgresql schema

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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

1
2
3
4
5
6
7
8
9
10
11
12
13
@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

1
2
3
4
5
6
7
Role count2
Customer count2
list count2
-------
Role count0
Customer count0
list count2

 

Reason

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 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

You might also like

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 […]


Read More..


Write To Me

Hire me shiva bhusal
We'll never share your email with anyone else.
I'll never share your email with anyone else.