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.
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 isstring
, otherwise number of bytes to be used for storagedefault
: Default value for the columnnull
: Boolean indicating if column can containnull
valuesprecision
: Precision fornumeric
anddecimal
columnsscale
: Scale fornumeric
anddecimal
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_reference comes in handy to get this done with a single schema statement.
Supported options for add_reference
type
: Datatype for the new column being addedindex
: Boolean indicating if index needs to be added. Defaults totrue
.null
: Boolean indicating if column can containnull
values. Defaults totrue
.polymorphic
: If set totrue
, an addition column with_type
name is added.foreign_key
: Foreign key constraint with the associated table. Defaults tofalse
.
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
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox