Can I add comments to a table or column using ActiveRecord Migrations?

In Rails 5 you can use the change_column:

class AddCommentsToReferences < ActiveRecord::Migration[5.2]
  def up
    change_column :references, :achievement_id, :integer, comment: 'Achievement'
    change_column :references, :object_id, :integer, comment: 'Achievement object id'
  end
end

don't forget write correct column_type as third parameter.


There is a gem called pg_comment that will add this functionality if you are using postgresql.

The gem adds extra commands to add the comments. Note that the syntax in postgresql is different than in mysql, and I guess that is why there is no general ActiveRecord implementation.

For example:

create_table :stuff do |t|
  t.integer :some_value
end
set_table_comment :stuff, 'This table stores stuff.'
set_column_comment :stuff, :some_value, 'Stores some value'

This could get pretty verbose, but I know there are some nice tools that make use of this.

Secondly, Rails indeed allows you to manage your schema from within rails (and that is awesome), it may seem sufficient to document your migrations, but after a while nobody looks at the migrations anymore. And you are stuck with an undocumented schema.

In the oracle-enhanced adapter this feature is available from the start, and has just the same syntax as you proposed.

Unfortunately I have not found a similar gem or solution for MySQL.


The migration_comments gem mentioned in a comment to the original question appears to be the best cross-database solution for this need. In addition to providing migrations support for adding table and column comments, the gem also annotates the schema.rb file to include all of the comments. Perfect for my company's needs (large legacy rails app where the database model is ambiguous and also shared with a team of analysts writing native SQL reports).