influitive / apartment

Database multi-tenancy for Rack (and Rails) applications
2.68k stars 461 forks source link

Rails 5, System tests, Sometimes table names not change when switch to tenant #489

Closed Xosmond closed 2 years ago

Xosmond commented 6 years ago

Hello, I have a problem with Apartment because I have found that table names are not correct sometimes on my tests:

Apartment::Tenant.switch! "test"
ApplicationRecord.descendants.each do |model|
  puts model.name
  puts model.table_name
end

This code generates mostly time:

Company
public.companies
TaxType
public.tax_types
Permission
public.permissions
User
users
Setting
settings
Role
roles

But only sometimes:

Company
public.companies
TaxType
public.tax_types
Permission
public.permissions
User
test.users
Setting
test.settings
Role
test.roles

I had to manually change them:

(ApplicationRecord.descendants - public_models).each do |model|
    model.table_name = "test." + model.table_name unless /test.*/.match(model.table_name)
end

Any idea why sometimes this is happening?

PD: Complete code is on Stackoverflow question, I think I should delete that question.

meganemura commented 6 years ago

@Xosmond

Would you please give us more information about your configurations like as follows.

Xosmond commented 6 years ago

@meganemura Here is the information:

module Apartment module Elevators class MyElevator < Apartment::Elevators::FirstSubdomain def call(env) request = Rack::Request.new(env) database = @processor.call(request) if database result = Apartment::Tenant.switch!(database) rescue "notfound" if result == "notfound" Rails.logger.error "Error: Apartment says tenant was not found for #{database.inspect}" raise ActionController::RoutingError.new('Not Found') else @app.call(env) end else @app.call(env) end end end end end

Apartment.configure do |config| config.excluded_models = %w{ Company TaxType Permission } config.tenant_names = lambda { Company.pluck :subdomain } end

Rails.application.config.middleware.use Apartment::Elevators::MyElevator

*Note: The custom elevator is just for manage the TenantNotFound Error, I got the same problem without the custom elevator.

- Rails: 

rails (5.1.4) activerecord (5.1.4)



- Ruby: `ruby 2.3.5p376 (2017-09-14 revision 59905) [x86_64-darwin16]`
acrogenesis commented 6 years ago

@Xosmond were you able to solve this I'm having the same problem

Xosmond commented 6 years ago

@acrogenesis As I said I had to manually change the table names on the before suite callback of rspec (depending of your tenant name for tests):

(ApplicationRecord.descendants - public_models).each do |model|
    model.table_name = "test." + model.table_name unless /test.*/.match(model.table_name)
end
henkesn commented 6 years ago

This also happens when not using an elevator at all. A random client db is used when not switching to a specific tenant. I don't know if this is fixable without elevator.

Xosmond commented 2 years ago

Closing due to no recent activity.