Apartment gem, tenant databases and MySQL

Oh, the fun it is.

I'm working on an application that will use the apartment gem and I've been needing to drop and recreate the database. I still prefer to work with MySQL and haven't jumped ship to the popular Postgres. MySQL doesn't seem to have as much support for the Apartment gem that Postgres does.

The out of the box functionality for running rails db:reset will simply drop and recreate your development and test environment databases and not touch any Apartment generated tenant databases that may have been created while developing and testing.

I decided to create a rake task since I've found myself dropping the tenant database plenty of times over.

Create a file in lib/tasks, I named it drop_tenants.rake.

Within the rake file add:

namespace :apartment do
	desc 'drop current tenants before performing database reset'
		task :drop_tenants => :environment do
			c = Mysql2::Client.new(host: "localhost", username: "root", password: "password")
			tenant_dbs = User.pluck :subdomain

          tenant_dbs.each do |db|
              r = c.query("DROP DATABASE #{db};")
              puts "Dropped #{db}"

This will get you the command rake apartment:drop_tenants so you can prepend this to when you run rake db:reset you'll simply just run rake apartment:drop_tenants db:reset and you're good to go!