こんにちは寝る

古い記事の情報は参考程度にお願いします

Railsのhas_one、has_many、belongs_toのメモ

概要

RailsのActive Recordで利用されるリレーションがたまにぐちゃぐちゃするのでメモ

例えばとあるブログサービスのDBだとして

[users]ユーザー情報
id
user_profile_id
name
address

[posts]投稿記事
id
user_id
content

[user_profile]ユーザーのプロフィール
id
age
description

has_one

ユーザーはプロフィールを1つもつ。

1:1であるこの時

ユーザーはプロフィールに属している → belongs_to
プロフィールはユーザーを持っている → has_one

has_many

ユーザーは投稿記事を複数個もつ。

1:nであるこの時

投稿記事はユーザーに属している → belongs_to
ユーザーは投稿記事を複数個持っている → has_many

まとめ

対象テーブルのidを持っている側に belongs_to が付く。

参照