LoginSignup
2
0

Railsアソシエーション: 中間テーブルを使用した関連性の構築

Last updated at Posted at 2023-12-22

多対多のアソシエーションとは?

多対多のアソシエーションは、2つのモデル間に直接の関連性を持たせる代わりに、中間テーブルを使用して関連を構築します。これにより、柔軟性が向上します。

例: 学生と科目の多対多のアソシエーション

Studentモデル

class Student < ApplicationRecord
  has_many :enrollments
  has_many :courses, through: :enrollments
end

Courseモデル

class Course < ApplicationRecord
  has_many :enrollments
  has_many :students, through: :enrollments
end

Enrollmentモデル

class Enrollment < ApplicationRecord
  belongs_to :student
  belongs_to :course
end

この例では、StudentとCourseが多対多のアソシエーションを持ち、中間モデルとしてEnrollmentが関連付けられています。
image.png
これで、学生(Studentモデル)と科目(Courseモデル)が中間テーブル(Enrollmentモデル)を介して関連付けられ、柔軟で拡張性のあるデータモデルが構築されました。

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