0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Railsで多対多の関係を作るなら中間テーブル!便利な理由と使い方

Posted at

Railsでアプリを作っていると、「ユーザーが複数のタグを持てて、タグも複数のユーザーに紐づく」ような関係が出てきます。

こうした多対多(many-to-many)の関係を作るときに必要なのが、中間テーブル(中間モデル)です。

🔁 多対多の関係とは?

例:
• ユーザーは複数のタグを持てる
• タグは複数のユーザーに使われる

これを表すためには、直接userとtagを結びつけるのではなく、間に「user_tags」という中間テーブル(モデル)を作成します。

🧱 中間テーブル(モデル)を作ってみよう

まずは中間テーブル用のモデルを作ります。

rails g model UserTag user:references tag:references
rails db:migrate

これで user_tags テーブルが作成され、user_id と tag_id を持つようになります。

🔗 モデルに関連づけを記述

Userモデル

# user.rb
class User < ApplicationRecord
  has_many :user_tags
  has_many :tags, through: :user_tags
end

Tagモデル

#tag.rb
class Tag < ApplicationRecord
  has_many :user_tags
  has_many :users, through: :user_tags
end

UserTagモデル(中間モデル)

# user_tag.rb
class UserTag < ApplicationRecord
  belongs_to :user
  belongs_to :tag
end

ポイントは、中間モデルでは belongs_to を使って明示的に関連付けること。そして親のモデルでは has_many :through を使って、多対多の関係を定義します。

✍️ データの追加方法(手動で行う例)

user = User.first
tag = Tag.first

user.tags << tag

Railsが裏で UserTag を作ってくれます!
上記は例なので、実際のコードはコントローラーのアクションに記述すると良いでしょう。

📌 便利な理由

理由 詳細
複雑な関係を整理できる 中間モデルに属性を追加することも可能(例:紐づいた日時など)
RESTfulな設計にしやすい モデルごとに役割を分けて整理できる
ActiveRecordで直感的に扱える user.tags のようなアクセスが可能になる
バリデーションも中間モデルで管理できる データ整合性も担保しやすい

📝 まとめ

・多対多は中間モデル(中間テーブル)を使って構築
・中間モデルには belongs_to、親モデルには has_many :through
・データ追加・取得もActiveRecordで直感的に書ける
・中間モデルには属性やバリデーションを追加して拡張可能

🏁 おわりに

中間テーブルは、一見複雑そうに見えて実は設計をシンプルに保つための必須テクニックです。
Railsではhas_many :throughを正しく使うことで、柔軟で強力な多対多関係を簡単に構築できます!

普段の勉強記録や日々の学びはこちらのはてなブログで投稿しています。
技術の基礎から実践まで、わかりやすくまとめているのでぜひチェックしてみてください!

▶︎はてなブログ:育児パパエンジニアの勉強記録
https://taaa-0991.hatenablog.com/

ご質問・ご指摘があれば、コメントやXでお気軽にどうぞ!
👉[@taaa_099]( https://x.com/taaa_099 )

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?