1
3

More than 3 years have passed since last update.

Rails テーブルの制約について

Posted at


Rails初心者の備忘録です。

制約とは

Railsでテーブルのカラムやデータに制限を加え、想定通りの値が入るようにします。

例えば郵便番号のように数値のデータが欲しいとき、文字列が入ってしまうと機能がおかしくなってしまうこともあります。
そのため、制約を設定します。

制約の種類

データ型

一般的によく使われているのがデータ型で、以下のようなものがあります。

string 短い文字
text 長い文字
integer 数値(整数)
float 数値(浮動小数)
date 日付
datetime 日時
time 時刻
boolean 真偽

NOT NULL制約

空欄を禁止する制約です。null: falseを付けます。

class CreatePostImages < ActiveRecord::Migration[5.1]
  def change
    create_table :post_images do |t|
      t.text :shop_name  
      t.text :image_id, null: false  #これ
      t.text :caption
      t.integer :user_id
      t.timestamps
    end
  end
end

UNIQUE制約

重複を禁止する制約です。unique: trueを付けます。
例えば、同じユーザーネームを登録できないようにしたい時などに使えると思います。

class CreatePostImages < ActiveRecord::Migration[5.1]
  def change
    create_table :post_images do |t|
      t.text :shop_name, unique: true #これ
      t.text :image_id, null: false  
      t.text :caption
      t.integer :user_id
      t.timestamps
    end
  end
end

DEFAULT制約

初期値を設定しておく制約です。:default => ''を付けます。

class CreatePostImages < ActiveRecord::Migration[5.1]
  def change
    create_table :post_images do |t|
      t.text :shop_name, null: false  
      t.text :image_id, unique: true 
      t.text :caption, :null => false, :default => 'これは例です。'  #これ 
      t.integer :user_id
      t.timestamps
    end
  end
end

主キー制約

主キーが必ずあって、重複もしてはいけないという制約です。idなどでよく使われるみたいです。
Railsでは、テーブルを作成する際にidカラムに元々実装されています。

外部キー制約

IDなどのキーを利用してテーブルとテーブルを関連付けているとき、親元のテーブルにデータが存在していなければいけないという制約です。

やり方はいろいろあるみたいですが、reference型のものを記載します。
t.reference :userの後にforeign_key: trueを付けます。

このとき、カラム名は`user_idで、自動でインデックスを割り振ってくれます。嬉しい。笑

class CreatePostImages < ActiveRecord::Migration[5.1]
  def change
    create_table :post_images do |t|
      t.text :shop_name, null: false  
      t.text :image_id, unique: true 
      t.text :caption, :null => false, :default => 'これは例です。' 
      t.references :user, foreign_key: true  #これ 
      t.timestamps
    end
  end
end


他にもいろいろとあるみたいですが、重要なものをメモしてみました。

参考にしたサイト

Railsの外部キー制約とreference型について

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