LoginSignup
0
0

More than 1 year has passed since last update.

多対多のアソシエーションを設定する

Posted at

はじめに

railsで多対多のアソシエーションを設定する際に必要な知識を忘れないために記録に残します。
なお、テーブル間の関係は、userテーブルとroomテーブルが多対多の関係性であるとする。

アソシエーションの手順

railsにおいて、多対多のアソシエーションを表現するためには、中間テーブルという概念を利用する。
中間テーブルとは、2つのテーブル間に配置するテーブルのこと。

  • 中間テーブルに紐づくモデルを作成する

      % rails g model room_user
    
  • カラムを設定
    中間テーブルのマイグレーションファイルに外部キーを記載

      class CreateRoomUsers < ActiveRecord::Migration[6.0]
        def change
          create_table :room_users do |t|
            t.references :room, null: false, foreign_key: true
            t.references :user, null: false, foreign_key: true
            t.timestamps
          end
        end
      end
    
      % rails db:migrate
    
  • アソシエーションの設定

          # app/models/room.rb内
          class Room < ApplicationRecord
            has_many :room_users
            has_many :users, through: :room_users
          end
          
          # app/models/user.rb内
          class User < ApplicationRecord
            # Include default devise modules. Others available are:
            # :confirmable, :lockable, :timeoutable and :omniauthable
            devise :database_authenticatable, :registerable,
                   :recoverable, :rememberable,  :validatable
            validates :name, presence: true
          
            has_many :room_users
            has_many :rooms, through: :room_users
          end
          
          # app/models/room_user.rb内
          class RoomUser < ApplicationRecord
            belongs_to :room
            belongs_to :user
          end
    
0
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
0
0