1
0

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 5 years have passed since last update.

Rails でデータベース (MySQL) のカラムをユニーク(一意)にする。 migration model test

Last updated at Posted at 2017-03-09

大文字小文字

一意制限はデフォルトでは大文字小文字を区別しません ( A のあとに a はだめ ) 。
大文字小文字を区別したい場合は。
config/database.yml を変更します。

default:
  ...
  password:
  collation: utf8_bin

のように collation: utf8_bin を追加して rails db:migrate:resetとコマンドを実行すると、大文字小文字を区別して ( A のあとに a はおk )一意制限してくれるようになります。

migration

rails g migration AddIndexToUsersName
コマンドでマイグレーションファイルを生成して、

マイグレーションファイルを変更。

def change
end

def change
  add_index :users, :name, unique: true
end

validates

モデルファイルを変更。

class User < ApplicationRecord
end

class User < ApplicationRecord
  validates :name, uniqueness: { case_sensitive: false }
end

大文字小文字を区別する場合は、

class User < ApplicationRecord
  validates :name, uniqueness: true
end

test

以下の Gem を使用しています。
rspec-rails gem
shoulda-matchers gem

テストファイルを変更。

RSpec.describe User, type: :model do
end

RSpec.describe User, type: :model do
  it { is_expected.to validate_uniqueness_of(:name).case_insensitive }
end

大文字小文字を区別する場合は、

RSpec.describe User, type: :model do
  it { is_expected.to validate_uniqueness_of(:name) }
end
1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?