アソシエーションについて

今日の積み上げはアソシエーション

  1. 多対多の表示の仕方について
  2. 中間テーブル

1. 多対多の表示について

model/orgnizer.rb

class Organizer < ApplicationRecord
  has_many :request_lists, dependent: :destroy
  has_many :exhibitions, through: :request_lists
end

model/request_list.rb

  belongs_to :organazier
  belongs_to :exhibition

model/exhibition.rb

class Exhibition < ApplicationRecord
    has_many :request_lists, dependent: :destroy
    has_many :organizers, through: :request_lists
end

ポイントは dependent: :destroy' とthrough` dependentは親子関係があるモデルに適応できて、親が削除されれば子も削除される ここでは多対多なのでorganizerにもexhibtionにも設定している 多対多の構造を深掘りするために、exhibition.rbをもう少し詳しく見てみる

class Exhibition < ApplicationRecord
    has_many :request_lists, dependent: :destroy  #中間テーブルに対して紐づいている
    has_many :organizers, through: :request_lists #throughオプションを使って中間テーブルを通してorganizerと紐づいている
end

exhibitionに紐づいたorganizerを表示させたい時はそれぞれにデータを入れる。

  • リレーションの作成
exhibiton.request_list.create(oranizer_id:1,exhibition_id: 1)
  • 表示
exhibition.organizers

2.中間テーブル

中間テーブルは 'rails g model request_list.rb カラム名' で作成。

model/request_list.rb

  belongs_to :organazier
  belongs_to :exhibition