primary_key 主キーを指定する

使用可能な関連付け

  • belongs_to
  • has_many
  • has_one

対となる関連に指定するオプション

なし

概要

主キー名にid以外を指定する場合に利用する。

念のため注記しておくと、ここで挙げている例はSQLite3で動作確認を行ってはいるものの、主キーを変える場合のベストプラクティスになっているかは確認していない。

# 主キーをULIDに変える
class CreateProfiles < ActiveRecord::Migration[8.0]
  def change
    create_table :profiles, primary_key: [:ulid] do |t|
      t.column :ulid, 'CHAR(26)', null: false
      t.timestamps
    end
  end
end

# こちらは主キーの変更を省略
class CreateAuthors < ActiveRecord::Migration[8.0]
  def change
    create_table :authors do |t|
      t.column :profile_ulid, 'CHAR(26)', null: false
      t.timestamps
    end
    add_foreign_key :authors, :profiles, column: :profile_ulid, primary_key: :ulid
  end
end

Model定義は以下のようにする。

class Profile < ApplicationRecord
  self.primary_key = :ulid
  # 相手の外部キーとしてforeign_keyを指定
  has_one :author, foreign_key: :profile_ulid

  before_save do
    # ULIDではないがサンプルなのでRandomで代替
    self.ulid = Random.rand.to_s
  end
end

class Author < ApplicationRecord
  # 相手の主キーとしてprimary_key、自分の外部キーとしてforeign_keyを指定
  belongs_to :profile, primary_key: :ulid, foreign_key: :profile_ulid
end