LoginSignup
25
31

More than 5 years have passed since last update.

カラムにかける制約について整理

Last updated at Posted at 2017-05-20

データベースのカラムの制約についてメモ。

カラムの制約

制約とは

特定のデータの保存を許さないためのバリデーション。
例えば同じニックネームのユーザーを登録できないようにする、メールアドレスが空のユーザーは保存ができないようにする、といったことができるようになる。

なんのために制約をかけるのか

不正なデータや予期せぬデータが保存されることを防ぐため。

制約の種類とかけ方

主に以下の4つ。

NOT NULL制約 (Not Null Constraint)

テーブルの属性値にNULL(空の値)が入ることを許さない制約。
絶対に値が必要なカラムに対してかける。

マイグレーションファイルでカラムを追加する時に書く。

【例】nameというカラムにNULLが入ることを許さない

t.string :name, null: false

一意性制約 (Unique Constraint)

テーブル内で重複するデータを禁止する制約。

【例】usersテーブルにemailというカラムを追加する際、emailカラムには重複した値が入らないようにする

class AddEmailToUsers < ActiveRecord::Migration
  def change
    add_column :users, :email, :string # 型がstringのemailカラムを追加する
    add_index :users, :email, unique: true # emailカラムに一意性制約をかける
  end
end

主キー制約(Primary Key Constraint)

主キーである属性値が必ず存在してかつ重複していないことを保証する制約。
Railsでは主キーはidカラムとして自動で生成され、重複しないようにできている。

外部キー制約(Foreign Key Constraint)

外部キーに対応するレコードが必ず存在することを保証する制約。

【例】studentsテーブルを生成し、classroomとのアソシエーションに外部キー制約を設定する

class CreateStudents < ActiveRecord::Migration
  def change
    create_table :scores do |t|
      t.string :name
      t.references :classroom, foreign_key: true
      t.timestamps null: false
    end
  end
end
25
31
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
25
31