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: falseThe 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 containnullvaluesprecision: Precision fornumericanddecimalcolumnsscale: Scale fornumericanddecimalcolumns
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
IDof 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_idadd_reference comes in handy to get this done with a single schema statement.
add_reference :products, :user, null: false, foreign_key: trueSupported 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 containnullvalues. Defaults totrue.polymorphic: If set totrue, an addition column with_typename 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
