LoginSignup
1
2

More than 3 years have passed since last update.

【Rails】多対多の作成

Last updated at Posted at 2020-12-18

本投稿の目的

・Railsについての議事録です。


学習に使った教材

Udemyの以下2つの教材を参考にまとめました。
"はじめてのRuby on Rails入門-RubyとRailsを基礎から学びWebアプリケーションをネットに公開しよう"
"フルスタックエンジニアが教える 即戦力Railsエンジニア養成講座"


○多対多の関係とは?

・複数のcolumnが相互に紐づいたmodel同士の関係
・例):掲示板アプリのboard とtagのような関係 (投稿内容は異なるがtagが同じような投稿は多対多の関係)

○紐付けのポイント

・中間テーブルを用意する (本投稿での説明では,model(中)と定義)
・中間テーブルは [:id,多1_id,多2_id] のみのシンプルな構造

○紐付け設定方法

①model多1とmodel多2を普通にgenerateする

rails g <model(多)1> <column情報>
rails g <model(多)2> <column情報> 

②中間テーブルをgenerateする

rails g model <model(中)> <model(多)1>:references <model(多)2>:references

・中間テーブルは通常は "model(多)1_model(多)2_relations" という名前が一般的
・model名称は全て小文字,単数形でOK

③migrationを実行

rails db:migrate

・①②で設定したmodelがdbのtableに反映される

④中間テーブルのmodelへの記述

model(中).rb
class model() < ApplicationRecord
  belongs_to :model()1
  belongs_to :model()2
end

・この記述はgenerate時に自動記述
・belongs_toが2つ設定済みのためノータッチでOK

⑤moel(多)1のmodelへの処理

model(多)1.rb
class model()1 < ApplicationRecord
has_many :<model()s>
has_many :<model()2s>, through: :<model()s>
end

through: :<model(中)s> は,2つのmodel間にmodel(中)を経由するという意味
・(model(多)1 → model(中) → model(多)2 という意味)
・中間テーブルを経由することをここで記述して置く必要がある
・model名は複数形で記述

⑥model(多)2のmodelへの処理

model(多)2.rb
class model()2 < ApplicationRecord
has_many :<model()s>
has_many :<model()1s>, through: :<model()s>
end

・model(多)1と同様に2つのhas_manyを設定
・model名は複数形で記述


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