Masatoshi Nishiguchi
Software Engineer

Many-to-many relationship in Rails

rails postgresql active_record database

Adding a many to many relationship between the following two models:

Create a migration file to create a join table.

rails g model Favorite user:references song:references

db/migrate/20160629144158_create_favorites.rb

class CreateFavorites < ActiveRecord::Migration
  def change
    create_table :favorites do |t|
      t.references :song, index: true, foreign_key: true
      t.references :user, index: true, foreign_key: true

      t.timestamps null: false
    end
  end
end

The join table

app/models/favorite.rb

class Favorite < ActiveRecord::Base
  belongs_to :song
  belongs_to :user
end

Two models accessing each other through the join table

app/models/user.rb

class User < ActiveRecord::Base
  ...
  has_many :favorites, dependent: :destroy
  has_many :songs, through: :favorites
  ...

app/models/song.rb

class Song < ActiveRecord::Base
  ...
  has_many :favorites, dependent: :destroy
  has_many :users, through: :favorites
  ...

References