5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Rails】一意性を保つバリデーションの実装

Posted at

#一意性バリデーションの実装に必要なタスク

  1. アプリ側に記述(uniqueness: true)
  2. データベース側に記述(unique: true)

#アプリ側に記述

models/user.rb
validates :email, uniqueness: true

#データベース側に記述

$ rails g migration add_column_to_users
add_column_to_users.rb
def change
  add_index :users, :email, unique: true
end
$ rails db:migrate

テーブルのカラムに一意性を持たせるには、インデックスの作成も必要になる。
理由は、全てのデータを検索することで、過去のデータと重複しているか確認できるため。

5
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?