Add references rails migration

class AddReferencesToTableName < ActiveRecord::Migration[6.0]
  def change
    add_reference :table_name, :related_table, foreign_key: true
  end
end

Explanation:

  1. class AddReferencesToTableName: Defines a new migration class named AddReferencesToTableName. Migration classes in Rails are used to modify the database schema over time.

  2. < ActiveRecord::Migration[6.0]: Indicates that this migration inherits from the ActiveRecord::Migration class and specifies the Rails version (6.0) to use the appropriate methods.

  3. def change: Defines a method named change within the migration class. The change method is a special method in Rails migrations that represents the modifications to be made to the database.

  4. add_reference :table_name, :related_table, foreign_key: true: Adds a reference column to the table_name table that references the related_table. This creates a foreign key constraint between the two tables, ensuring referential integrity.

  5. :table_name: Replace with the actual name of the table to which you want to add a reference column.

  6. :related_table: Replace with the actual name of the table being referenced.
  7. 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.