Search code examples
ruby-on-railspostgresql

Rails: how to add comment on fields?


I've found a piece of code, can anyone let me know what comment: is mostly used for and how to add comments on table name and fields?

I use PostgreSQL.

  create_table "sun", force: :cascade, comment: "The center" do |t|
    t.string   "distance",                     comment: "Long way"
    t.string   "energy",                       comment: "Super power"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

Solution

  • In Rails 5, you are allowed to specify comments for tables, column and indexes in database migrations. These comments are stored in database itself. You are looking at the schema.rb which display the comments.

    Currently only MySQL and PostgreSQL supports adding comments.

    Comments are simply comments - they give a short summary of what the table/column is.

    To add a comment during a migration you simply add comment: 'This is an explanatory comment' to the migration, obviously replacing the comment text you want.

    This is shown in an example migration below where I am adding a column to a table:

    class AddSomethingToSometable < ActiveRecord::Migration
      def change
        add_column :sometable, :something, :integer, comment: 'This is an explanatory comment'
      end
    end
    

    For more information see the original pull on GitHub