🔗

Associations(関連)

has_many、belongs_to — モデル間の関係設定

ActiveRecord Associationはモデル間の関連をRubyコードで宣言する機能です。

基本関連:

class User < ApplicationRecord
  has_many :posts              # User 1:N Post
  has_one :profile             # User 1:1 Profile
end

class Post < ApplicationRecord
  belongs_to :user             # postsテーブルにuser_id外部キー
  has_many :comments
  has_many :tags, through: :post_tags  # N:M関係
end

使用:

user.posts                    # そのユーザーの全ポスト
user.posts.create(title: '...')  # 関連を通じた生成
post.user                     # ポストの作成者

オプション:

  • dependent: :destroy — 親削除時に子も削除

  • class_name: — 関連クラス名指定(規約外)

  • foreign_key: — 外部キーカラム名指定

  • inverse_of: — 逆関連を明示

構造ダイアグラム

1:N (has_many / belongs_to)
User
has_many :posts
1 ←→ N
Post
belongs_to :user
user_id 外部キー
1:1 (has_one / belongs_to)
User
has_one :profile
1 ←→ 1
Profile
belongs_to :user
user_id 外部キー
N:M (has_many :through)
Post
has_many :tags,
through: :post_tags
N
PostTag
post_id + tag_id
N
Tag
has_many :posts,
through: :post_tags
ポイント: <strong>宣言的な関係設定</strong> → user.posts, post.user等のメソッドが自動生成

キーポイント

1

belongs_to :user — このテーブルにuser_id外部キーがあることを宣言

2

has_many :posts — 相手モデルが自分の外部キーを持つことを宣言

3

has_one :profile — 1:1関係を宣言

4

has_many :tags, through: :post_tags — 中間テーブルを通じたN:M関係

5

dependent: :destroyオプションで連鎖削除設定

6

user.posts、post.user等のメソッドが自動生成

メリット

  • 宣言的で関連が一目でわかる
  • 関連を通じたCRUDメソッド自動生成
  • eager loadingでN+1問題を解決
  • 外部キー規約で設定最小化

デメリット

  • 複雑な関連はコード追跡が困難
  • dependentオプションの間違いでデータ損失
  • ポリモーフィック関連は複雑
  • counter_cache等最適化オプションの学習が必要

ユースケース

User-Post 1:N関係 Post-Tag N:M関係 User-Profile 1:1関係 has_many :throughで複雑な関係を表現