When developing a Rails app, have there been times when you're wondering "what properties/columns does this model have"? The easiest way to find out is by inspecting db/schema.rb, but that gets annoying quickly. If only there's a way to keep your schema closer to you. Enter the annotate gem.

This gem adds comments summarizing a specific model's schema. Such comments are added to the top or bottom of each ActiveRecord model, test or RSpec spec, FactoryBot factory, etc. Here's an example:

# == Schema Info
# Table name: line_items
#  id                  :integer(11)    not null, primary key
#  quantity            :integer(11)    not null
#  product_id          :integer(11)    not null
#  unit_price          :float
#  order_id            :integer(11)

 class LineItem < ActiveRecord::Base
   belongs_to :product

Installation and usage

You can use it by adding it to your Gemfile as follows:

group :development do
  gem 'annotate'

Then install the gem bundle and the Rails hooks:

bundle install
./bin/rails g annotate:install

Now you are ready to go! Run this to have it add comments:

bundle exec annotate

Notes and caveats

The ./bin/rails g annotate:install actually creates a file lib/tasks/auto_annotate_models.rake, which ensures that every time you run ./bin/rails db:migrate, the annotate command is run automatically for you. This means that most of the time you don't need to run annotate manually.

Still, it's not perfect. So sometimes you should double-check by running annotate manually and check whether anything has been missed.

Also, the gem is very picky about names, and there's no way to customize that behavior. The biggest issue I've run into is that my FactoryBot factory files must have the same name as the model, in underscore plural format. So going along with the LineItem example, the factory file must be called spec/factories/line_items.rb. line_item.rb won't do.

The gem also won't pick up everything in the schema, just the things supported by default by Rails. For example things like database constraints or stored procedures won't be picked up in the comments.

Still, the gem is very useful. Happy devving!