Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
A

active_record_doctor

> 后端框架
Open source

Identify database issues before they hit production.

1.9K stars0 likes0 views
WebsiteGitHub

About

Identify database issues before they hit production.

Active Record Doctor

Active Record Doctor helps to keep the database in a good shape. Currently, it can detect:

  • extraneous indexes - active_record_doctor:extraneous_indexes
  • unindexed deleted_at columns - active_record_doctor:unindexed_deleted_at
  • missing foreign key constraints - active_record_doctor:missing_foreign_keys
  • models referencing undefined tables - active_record_doctor:undefined_table_references
  • uniqueness validations not backed by a unique index - active_record_doctor:missing_unique_indexes
  • missing non-NULL constraints - active_record_doctor:missing_non_null_constraint
  • missing presence validations - active_record_doctor:missing_presence_validation
  • incorrect presence validations on boolean columns - active_record_doctor:incorrect_boolean_presence_validation
  • mismatches between model length validations and database validation constraints - active_record_doctor:incorrect_length_validation
  • incorrect values of dependent on associations - active_record_doctor:incorrect_dependent_option
  • primary keys having short integer types - active_record_doctor:short_primary_key_type
  • mismatched foreign key types - active_record_doctor:mismatched_foreign_key_type
  • tables without primary keys - active_record_doctor:table_without_primary_key
  • tables without timestamps - active_record_doctor:table_without_timestamps

It can also:

  • index unindexed foreign keys - active_record_doctor:unindexed_foreign_keys

Installation

In order to use the latest production release, please add the following to your Gemfile:

ruby
gem 'active_record_doctor', group: [:development, :test]

and run bundle install. If you'd like to use the most recent development version then use this instead:

ruby
gem 'active_record_doctor', github: 'gregnavis/active_record_doctor', group: [:development, :test]

That's it when it comes to Rails projects. If your project doesn't use Rails then you can use active_record_doctor via Rakefile.

Additional Installation Steps for non-Rails Projects

If your project uses Rake then you can add the following to Rakefile in order to use active_record_doctor:

ruby
require "active_record_doctor"

ActiveRecordDoctor::Rake::Task.new do |task|
  # Add project-specific Rake dependencies that should be run before running
  # active_record_doctor.
  task.deps = []

  # A path to your active_record_doctor configuration file.
  task.config_path = ::Rails.root.join(".active_record_doctor.rb")

  # A Proc called right before running detectors that should ensure your Active
  # Record models are preloaded and a database connection is ready.
  task.setup = -> { ::Rails.application.eager_load! }
end

IMPORTANT. active_record_doctor expects that after running deps and calling setup your Active Record models are loaded and a database connection is established.

Usage

active_record_doctor can be used via rake or rails.

You can run all available detectors via:

bundle exec rake active_record_doctor

You can run a specific detector via:

bundle exec rake active_record_doctor:extraneous_indexes

Continuous Integration

If you want to use active_record_doctor in a Continuous Integration setting then ensure the configuration file is committed and run the tool as one of your build steps -- it returns a non-zero exit status if any errors were reported.

Obtaining Help

If you'd like to obtain help on a specific detector then use the help sub-task:

bundle exec rake active_record_doctor:extraneous_indexes:help

This will show the detector help text in the terminal, along with supported configuration options, their meaning, and whether they're global or local.

Debug Logging

It may be that active_record_doctor fails with an exception and it is hard to tell what went wrong. For easier debugging, use ACTIVE_RECORD_DOCTOR_DEBUG environment variable. If active_record_doctor fails for some reason for your application, feel free to open an issue or a PR with the fix.

ACTIVE_RECORD_DOCTOR_DEBUG=1 bundle exec rake active_record_doctor

Configuration

active_record_doctor can be configured to better suit your project's needs. For example, if it complains about a model that you want ignored then you can add that model to the configuration file.

If you want to use the default configuration then you don't have to do anything. Just run active_record_doctor in your project directory.

If you want to customize the tool you should create a file named .active_record_doctor.rb in your project root directory with content like:

ruby
ActiveRecordDoctor.configure do
  # Global settings affect all detectors.
  global :ignore_tables, [
    # Ignore internal Rails-related tables.
    "ar_internal_metadata",
    "schema_migrations",
    "active_storage_blobs",
    "active_storage_attachments",
    "action_text_rich_texts",

    # Add project-specific tables here.
    "legacy_users"
  ]

  # Detector-specific settings affect only one specific detector.
  detector :extraneous_indexes,
    ignore_tables: ["users"],
    ignore_indexes: ["accounts_on_email_organization_id"]
end

The configuration file above will make active_record_doctor ignore internal Rails tables (which are ignored by default) and also the legacy_users table. It'll also make the extraneous_indexes detector skip the users table entirely and will not report the index named accounts_on_email_organization_id as extraneous.

Configuration options for each detector are listed below. They can also be obtained via the help mechanism described in the previous section.

Regexp-Based Ignores

Settings like ignore_tables, ignore_indexes, ignore_models and so on accept list of identifiers to ignore. These can be either:

  1. Strings - in which case an exact match is needed.
  2. Regexps - which are matched against object names, and matching ones are excluded from output.

For example, to ignore all tables starting with legacy_ and all models under the Legacy:: namespace you can write:

ruby
ActiveRecordDoctor.configure do
  global :ignore_tables, [
    # Ignore all legacy tables.
    /^legacy_/
  ]
  global :ignore_models, [
    # Ignore all legacy models.
    /^Legacy::/
  ]
end

Indexing Unindexed Foreign Keys

Foreign keys should be indexed unless it's proven ineffective. However, Rails makes it easy to create an unindexed foreign key. Active Record Doctor can automatically generate database migrations that add the missing indexes. It's a three-step process:

  1. Generate a list of unindexed foreign keys by running
bash
bundle exec rake active_record_doctor:unindexed_foreign_keys > unindexed_foreign_keys.txt
  1. Remove columns that should not be indexed from unindexed_foreign_keys.txt as a column can look like a foreign key (i.e. ending with _id) without being one.

  2. Generate the migrations

bash
rails generate active_record_doctor:add_indexes unindexed_foreign_keys.txt
  1. Run the migrations
bash
bundle exec rake db:migrate

Supported configuration options:

  • enabled - set to false to disable the detector altogether
  • ignore_tables - tables whose foreign keys should not be checked
  • ignore_columns - columns, written as table.column, that should not be checked.

Removing Extraneous Indexes

Let me illustrate with an example. Consider a users table with columns first_name and last_name. If there are two indexes:

  • A two-column index on last_name, first_name.
  • A single-column index on last_name.

Then the latter index can be dropped as the former can play its role. In general, a multi-column index on column_1, column_2, ..., column_n can replace indexes on:

  • column_1
  • column_1, column_2
  • ...
  • column_1, column_2, ..., column_(n - 1)

To discover such indexes automatically just follow these steps:

  1. List extraneous indexes by running:
bash
bundle exec rake active_record_doctor:extraneous_indexes
  1. Confirm that each of the indexes can be indeed dropped.

  2. Create a migration to drop the indexes.

The indexes aren't dropped automatically because there are usually just a few of them and it's a good idea to double-check that you won't drop something necessary.

Also, extra indexes on primary keys are considered extraneous too and will be reported.

Note that a unique index can never be replaced by a non-unique one. For example, if there's a unique index on users.login and a non-unique index on users.login, users.domain then the tool will not suggest dropping users.login as it could violate the uniqueness assumption. However, a unique index on users.login, user.domain might be replaceable with users.login as the uniqueness of the latter implies the uniqueness of the former (if a given login can appear only once then it can be present in only one login, domain pair).

Supported configuration options:

  • enabled - set to false to disable the detector altogether
  • ignore_tables - tables whose indexes should never be reported as extraneous.
  • ignore_indexes - indexes that should never be reported as extraneous.

Detecting Unindexed deleted_at Columns

If you soft-delete some models (e.g. with paranoia) then you need to modify your indexes to include only non-deleted rows. Otherwise they will include logically non-existent rows. This will make them larger and slower to use. Most of the time they should only cover columns satisfying deleted_at IS NULL (to cover existing records) or deleted_at IS NOT NULL (to cover deleted records).

active_record_doctor can automatically detect indexes on tables with a deleted_at column. Just run:

bundle exec rake active_record_doctor:unindexed_deleted_at

This will print a list of indexes that don't have the deleted_at IS NULL clause. Currently, active_record_doctor cannot automatically generate appropriate migrations. You need to do that manually.

Supported configuration options:

  • enabled - set to false to disable the detector altogether
  • ignore_tables - tables whose indexes should not be checked.
  • ignore_columns - specific columns, written as table.column, that should not be reported as unindexed.
  • ignore_indexes - specific indexes that should not be reported as excluding a timestamp column.
  • column_names - deletion timestamp column names.

Detecting Missing Foreign Key Constraints

If User defines a belongs_to association to Profile then the underlying column (users.profile_id by convention) should be marked as a foreign key in the database. If it's not then it's possible to end up in a situation where a user is referencing a non-existent profile.

active_record_doctor can automatically detect foreign keys that could benefit from a foreign key constraint (a future version will generate a migration that add the constraint; for now, it's your job). You can obtain the list of missing foreign key constraints with the following command:

bash
bundle exec rake active_record_doctor:missing_foreign_keys

In order to add a foreign key constraint to users.profile_id use a migration like:

ruby
class AddForeignKeyConstraintToUsersProfileId

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubyactiverecorddatabaseperformancerails

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架