17
18

More than 5 years have passed since last update.

【Rails】中間テーブルの組み方

Posted at

中間テーブルを実装したい

以前の記事でお送りしたuserschoolのテーブルについて、
実際にコードで実装しようと思います。

user

id user
1 a
2 b
3 c
4 d

school

id school
1 A小学校
2 B中学校
3 C高校
4 D大学
5 E大学院
6 Foreign_University

user_school ←中間テーブル

id user school
1 a A小学校
2 a B中学校
3 a C高校
4 a D大学
5 b A小学校
6 b B中学校

モデルのアソシエーション

テーブルとテーブルに関係性を持たせるには、
モデルに記述を追加して、アソシエーションを構築します。

user.rb
class User < ApplicationRecord
 has_many :user_schools
 has_many :schools, through: :user_schools
end
school.rb
class School < ApplicationRecord
 has_many :user_schools
 has_many :users, through: :user_schools
end
user_schools.rb
class UserSchool < ApplicationRecord
 belongs_to :user
 belongs_to :school
end

親テーブルに
has_many :テーブル名(複数形)

子テーブルに
belongs_to :テーブル名(単数形)

のように記述します。

このとき、userテーブルとschoolテーブルは相互に複数のデータに関連を持ちます。
<aさんは、A小学校も、B小学校も卒業>
aさん→userテーブルのデータが、A小学校、B中学校、schoolテーブルに対して複数関連を持っている

<B中学校は、aさんも、bさんも卒業>
B中学校→schoolテーブルのデータが、aさん、bさん、userテーブルに対して複数関連を持っている

中間テーブルは子テーブル

user_schoolsのテーブルに入ってるデータは、
そのひとつのデータから見ると、userテーブル schoolテーブルともにひとつしかありません。

id user school
1 a A小学校

aA小学校もそれぞれuserテーブル、schoolテーブルにはひとつのみ>

そのため、中間テーブルのモデルにはbelongs_toの記述でアソシエーションを記述する点に注意が必要です。

今日はこのあたりで失礼します。

17
18
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
17
18