Rails add_reference vs add_column in migrations

Rails supports schema statements like add_reference and add_columns. They have different options and serve different purpose as illustrated in this post.

1. add_column in rails migrations

To add a new column to an existing table in Rails, we can write a migration using add_column schema statement as given below.

add_column :table_name, :column_name, :integer, default: 0, null: false

The above example will add a new column_name column, to table_name table.

Supported add_column options:

  • limit: Number of characters if column type is string, otherwise number of bytes to be used for storage
  • default: Default value for the column
  • null: Boolean indicating if column can contain null values
  • precision: Precision for numeric and decimal columns
  • scale: Scale for numeric and decimal columns

There are a few more options explained at add_column in Rails migration.

2. add_reference in rails migrations

Sometimes,

  • We have to add a column, that refers primary key ID of some other associated table.
  • Add index for the newly added column.

In that case, we go with add_column approach, the migration will become as given below.

add_column :products, :user_id, :integer, default: 0, null: false
add_index :products, :user_id

add_reference comes in handy to get this done with a single schema statement.

add_reference :products, :user, null: false, foreign_key: true
Supported options for add_reference
  • type: Datatype for the new column being added
  • index: Boolean indicating if index needs to be added. Defaults to true.
  • null: Boolean indicating if column can contain null values. Defaults to true.
  • polymorphic: If set to true, an addition column with _type name is added.
  • foreign_key: Foreign key constraint with the associated table. Defaults to false.

Conclusion

add_reference is just a shorthand for add_column and add_index combined. It offers more flexibility when adding constraint for associated tables.

References