LoginSignup
1
0

More than 3 years have passed since last update.

primary key メモ

Posted at

再度、理解があっているか確認のためメモ
あと言語化できるように

primary key とは

DBのキーのこと
DBのデータ(行、レコード)一意(他に同じデータがない)に識別する
ための項目のこと

【なんのためか】
「主キーの値が○○なデータ」と言えば
「あっ、このデータ(行、レコード)だな」とすぐに判断できるため

主キー」とも呼ばれる

役割

・テーブル検索のスピードを格段に早くする
・テーブルデータの整合性を保証する

Rails

・デフォルトでidが追加される仕様
・文字列とかを主キーに設定したい場合がある
→「id: false」で自動で主キーをIDにする設定を解除できる
→主キーに設定したいカラムに対して「primary_key: true」を設定します。

migrationファイル
class Hoge < ActiveRecord::Migration[5.2]
  def change
    # id: falseを追加
    create_table :hogehoge, id: false do |t| 
      # primary_key: trueを追加
      t.integer :user_id, null: false, primary_key: true
      t.string :name

メモ
複合キー(composite_primary_keys)
・composite_primary_keysというGem

参考記事

https://wa3.i-3-i.info/word1991.html
https://www.sejuku.net/blog/52356
http://www.code-magagine.com/?p=12207
https://qiita.com/tanutanu/items/6c53b5290eaa9bf905d3
https://qiita.com/belion_freee/items/8f8f1d1e5333da561fd8

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