It is a memorandum.
It is a unique constraint. Constraints when adding or updating data in DB. Gives the column its own uniqueness.
For example, by applying a unique constraint, when a user makes a new registration, an error can be returned if he / she tries to register with the same email address that has already been registered.
add_index :table name, [:Column name 1, :Column name 2, :Column name 3, ...(Continue)], unique: true
If the table name is contents and the column names are part_id and word, it will be as follows.
add_index :contents, [:part_id, :word], unique: true
Let's describe it in the change method of the migration file as follows.
Migration file
class CreateContents < ActiveRecord::Migration[6.0]
def change
create_table :contents do |t|
t.integer :part_id, null: false
t.string :word, null: false
t.references :user, null: false, foreign_key: true
t.timestamps
end
add_index :contents, [:part_id, :word], unique: true #This line.
end
end
For example, remove it from the change method and write it as follows.
Migration file
class CreateContents < ActiveRecord::Migration[6.0]
def change
create_table :contents do |t|
t.integer :part_id, null: false
t.string :word, null: false
t.references :user, null: false, foreign_key: true
t.timestamps
end
end
add_index :contents, [:part_id, :word], unique: true #This line.
end
If you run rails db: migrate in this state, you will get an error.
% rails db:migrate
-- add_index(:contents, [:part_id, :word], {:unique=>true})
-- add_index(:contents, [:part_id, :word], {:unique=>true})
rails aborted!
ActiveRecord::StatementInvalid: Mysql2::Error: Table 'hoge_development.contents' doesn't exist
Recommended Posts