-
Notifications
You must be signed in to change notification settings - Fork 8
Basic Tenancy with Apartment, Sidekiq and MySQL
Given that much of Apartment's documentation is very tied to Postgres and the specific use of the schemas feature of Postgres, this wiki page covers the specific use case of a multitenant Rails app using Apartment, Sidekiq and MySQL.
Please note that this is pre-release documentation based on the Flexible Switching fork of the Apartment gem which has not yet been merged into the main branch.
The one real limitation to understand is that there are connection issues at the lowest level of ActiveRecord that can cause issues with Apartment. These connection issues are addressed in Rails 5.1 at the ActiveRecord level and then enabled by turning on the use_schemas option in the apartment.rb initializer. While this sounds like the Postgres schemas feature, it is not. Setting this option configures Apartment to issue standard SQL use statements prior to queries. This prevents the thread safety issues associated with connection switching at the lowest levels of ActiveRecord. The one limitation with this is that it prevents switching to entirely different database servers for a given tenant.
This approach also restores the ability to use a threaded web server such as Puma since the thread safety issues are no longer a concern.
The two gems that you need are:
- apartment - this provides basic tenancy for a Rails application including subdomain style functionality such as foo.domain.com where foo is the name of the database
- apartment-sidekiq - this enhances sidekiq to pass in the current tenant with the sidekiq job
gem 'apartment', :git => "https://github.com/mikecmpbll/apartment.git", :branch => flexible-switching"
gem 'apartment-sidekiq'
Use the following command to generate the initializer
bundle exec rails generate apartment:install
config.use_schemas = true
Note: This needs to be done.