0
0

polymorphicと中間テーブルの違い

Posted at

polymorphicと呼ばれる、初めましての概念と出会ったので記録します。
polymorphic自体は理解したつもりだったのですが、中間テーブルの違いはなんなのかなと思った時に分からなかったので聞いてみました。

以下本文

ポリモーフィック(polymorphic)と中間テーブル(join table)は、データベース設計において多対多の関係を扱うための異なるアプローチです。それぞれの違いと特徴を以下に説明します。

ポリモーフィック(Polymorphic)

定義:

ポリモーフィック関連は、一つのモデルが複数の他のモデルに関連付けられる方法です。ポリモーフィック関連では、関連するテーブルに追加のカラムを使用して、関連付けのタイプを識別します。

使用例:

例えば、コメント(Comment)モデルが、記事(Article)や画像(Image)など、複数の異なるモデルに関連付けられる場合があります。この場合、ポリモーフィック関連を使用します。


# Migration to create comments table with polymorphic association
class CreateComments < ActiveRecord::Migration[6.0]
  def change
    create_table :comments do |t|
      t.text :content
      t.references :commentable, polymorphic: true, index: true
      t.timestamps
    end
  end
end

# Comment model with polymorphic association
class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end

# Article model
class Article < ApplicationRecord
  has_many :comments, as: :commentable
end

# Image model
class Image < ApplicationRecord
  has_many :comments, as: :commentable
end

特徴:

  • 複数の異なるモデルに関連付けられる。
  • commentable_typecommentable_idというカラムを持つ。
  • データベース設計がシンプルになることがある。

中間テーブル(Join Table)

定義:

中間テーブルは、多対多の関連を表現するために使用されるテーブルです。二つのテーブル間の関連を管理するために第三のテーブル(中間テーブル)を作成します。

使用例:

例えば、プロジェクト(Project)とユーザー(User)が多対多の関係にある場合、中間テーブルを使用します。


# Migration to create join table for projects and users
class CreateProjectsUsersJoinTable < ActiveRecord::Migration[6.0]
  def change
    create_table :projects_users, id: false do |t|
      t.belongs_to :project
      t.belongs_to :user
    end
  end
end

# Project model
class Project < ApplicationRecord
  has_and_belongs_to_many :users, join_table: :projects_users
end

# User model
class User < ApplicationRecord
  has_and_belongs_to_many :projects, join_table: :projects_users
end

特徴:

  • 二つのテーブル間の多対多の関係を管理する。
  • 中間テーブルには、関連する二つのモデルの外部キーが含まれる。
  • 関連情報を柔軟に拡張できる(例:役割や参加日などの追加属性)。

違いのまとめ

特徴 ポリモーフィック 中間テーブル
関係の種類 一対多、多対多 多対多
関連付けるモデルの数 複数の異なるモデルが可能 二つの特定のモデル
設計のシンプルさ 複数の異なるモデルと関連付ける場合にシンプルになることがある 多対多の関係の管理が必要な場合にシンプル
拡張性 関連タイプを動的に増やすのは難しい 中間テーブルに追加属性を持たせることで柔軟に拡張可能

以上がポリモーフィックと中間テーブルの違いです。それぞれのアプローチは、特定の要件やデータモデルに応じて適切に選択されます。

DB関連の知識は後々の個人開発を見据えて身につけたい知識です。
なのでしっかり勉強したいと思います。

0
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
0
0