問題一覧に戻る
初級Rails基礎
問題24: 関連付け基礎 - has_many/belongs_to
Active Recordの関連付け(アソシエーション)を使って、モデル間のリレーションシップを定義する方法を学習します。
📝 タスク 1: 1対多の関連(親側)
- Userが複数のPostを持つ関連を定義してください
📝 タスク 2: 1対多の関連(子側)
- PostがUserに属する関連を定義してください
📝 タスク 3: 多対多の関連
- Doctorが複数のPatientを持つ関連をthroughで定義してください
📝 タスク 4: 1対1の関連
- Userが1つのProfileを持つ関連を定義してください
# 1対多の関連(親側)
class User < ApplicationRecord
:posts
end
# 1対多の関連(子側)
class Post < ApplicationRecord
:user
end
# 中間テーブルを介した多対多
class Doctor < ApplicationRecord
has_many :appointments
has_many :patients, : :appointments
end
# 1対1の関連
class User < ApplicationRecord
:profile
end