LoginSignup
3
0

More than 1 year has passed since last update.

[Rails] uniquness バリデーションの警告

Posted at

開発環境

macOS: Big Sur
Rubyバージョン: 2.7.2
Railsバージョン: 6.0.3.7

目的

Rubocop が uniqueness バリデーションに対して出す次の警告を無くす。

警告

Rails/UniqueValidationWithoutIndex: Uniqueness validation should be with a unique index.

バリデーション定義

user.rb
class User < ApplicationRecord
  validates :name, uniqueness: true
end

解決策

name カラムに対して unique index をつける。

 t.index ["name"], unique: true

なぜ unique index が必要なのか。1つ目も理由は、確実にレコードをユニークにするためです。 Active Recordのバリデーションだけではレコードはユニークになりません。2つ目はパフォーマンス上の問題です。 indexがない状態でActive Recordのuniquenessバリデーションを使用するとパフォーマンスが悪化する恐れがあります。

最後に

以上で Rubocop の警告は無くなりました。
下手な説明ですが、読んでいただきありがとうございました。

3
0
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
3
0