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:
class CreateUsers < ActiveRecord::Migration[6.0]
: Defines a migration class namedCreateUsers
, which inherits fromActiveRecord::Migration[6.0]
.def change
: Begins the migration's change method where the table creation and modifications will be defined.create_table :users do |t|
: Initiates the creation of a table namedusers
. The block variablet
is used to define table columns.t.string :email, null: false
: Adds a column namedemail
to theusers
table with a string data type. Thenull: false
option ensures that this column cannot have a NULL value.t.timestamps
: Automatically addscreated_at
andupdated_at
columns to theusers
table to track record creation and modification times.end
: Closes the block for defining table columns withincreate_table
.add_index :users, :email, unique: true
: Adds an index on theemail
column of theusers
table. Theunique: true
option ensures that each value in theemail
column must be unique, preventing duplicate entries. ```