rails_schema_cleaner is a Ruby gem that helps keep your Rails database schema clean by identifying and removing orphaned tables (tables that do not have corresponding ActiveRecord models). It generates a migration file to drop these unused tables safely.
Add this gem to your Gemfile:
gem "rails_schema_cleaner"Then run:
bundle installAlternatively, install it manually:
gem install rails_schema_cleanerTo list all tables in the database that do not have an associated model, run:
bundle exec rails_schema_cleaner detectThis will return an array of orphaned table names.
To create a Rails migration file that drops these tables, run:
bundle exec rails_schema_cleaner cleanThis will generate a timestamped migration file in db/migrate/, e.g.:
db/migrate/20240228123456_drop_orphaned_tables.rbExecute the migration to drop the orphaned tables:
rails db:migrate- Works with Rails >=5.0
- Supports SQLite, PostgreSQL, and MySQL
- Fetches all database tables using
ActiveRecord::Base.connection.tables - Fetches all existing model table names using
ActiveRecord::Base.descendants.map(&:table_name) - Compares both lists and identifies tables that do not have an associated model
- Generates a Rails migration file to drop those tables
Run RSpec tests with:
rspecThis project is licensed under the MIT License.
Pull requests are welcome! Please open an issue to discuss any significant changes before submitting a PR.
Created by Hassan Murtaza.