create table index unique rails

class CreateUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :users do |t|
      t.string :email, null: false

      t.timestamps
    end

    add_index :users, :email, unique: true
  end
end

Explanation:

  1. class CreateUsers < ActiveRecord::Migration[6.0]: Defines a migration class named CreateUsers, which inherits from ActiveRecord::Migration[6.0].

  2. def change: Begins the migration's change method where the table creation and modifications will be defined.

  3. create_table :users do |t|: Initiates the creation of a table named users. The block variable t is used to define table columns.

  4. t.string :email, null: false: Adds a column named email to the users table with a string data type. The null: false option ensures that this column cannot have a NULL value.

  5. t.timestamps: Automatically adds created_at and updated_at columns to the users table to track record creation and modification times.

  6. end: Closes the block for defining table columns within create_table.

  7. add_index :users, :email, unique: true: Adds an index on the email column of the users table. The unique: true option ensures that each value in the email column must be unique, preventing duplicate entries. ```