Add references rails migration
class AddReferencesToTableName < ActiveRecord::Migration[6.0]
def change
add_reference :table_name, :related_table, foreign_key: true
end
end
Explanation:
class AddReferencesToTableName
: Defines a new migration class namedAddReferencesToTableName
. Migration classes in Rails are used to modify the database schema over time.< ActiveRecord::Migration[6.0]
: Indicates that this migration inherits from theActiveRecord::Migration
class and specifies the Rails version (6.0) to use the appropriate methods.def change
: Defines a method namedchange
within the migration class. Thechange
method is a special method in Rails migrations that represents the modifications to be made to the database.add_reference :table_name, :related_table, foreign_key: true
: Adds a reference column to thetable_name
table that references therelated_table
. This creates a foreign key constraint between the two tables, ensuring referential integrity.:table_name
: Replace with the actual name of the table to which you want to add a reference column.:related_table
: Replace with the actual name of the table being referenced.foreign_key: true
: Specifies that a foreign key constraint should be created to maintain the relationship between the tables.
Note: Make sure to replace :table_name
and :related_table
with the actual names of your tables. This migration is a generic example, and you should customize it according to your specific database schema and requirements.