More Complex Many to Many

This is a premium course, which you can purchase below.

Buy Now

Some many to many relationships are a bit more complex, such as relating customers to products through invoices (for instance). Let's see how to do this in Rails using a 'has many through' relationship.


I didn't pick the best example for this video (artists and tracks), but if you imagine that songs can be covered by many artists (think "Mack the Knife" or something), it works:

class Artist < ApplicationRecord
  has_many :albums
  has_many :tracks, through: :albums
end

The other end of the association needs to link back:

class Track < ApplicationRecord
  belongs_to :album
  belongs_to :media_type
  belongs_to :genre
  has_and_belongs_to_many :playlists
  has_many :artists, through: :album
end