● videoThe Rewrite
More Complex Many to Many

Unlock Revisiting Ruby on Rails
Subscribe for full access to every course, or buy this one on its own.
SECTION
The Rewrite
NEXT UP
A Look at Rails Tests
COURSE
Rails Revisited
33 lessons
About this lesson
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:
<span class="hljs-keyword">class</span> <span class="hljs-title class_">Artist</span> < <span class="hljs-title class_ inherited__">ApplicationRecord</span>
has_many <span class="hljs-symbol">:albums</span>
has_many <span class="hljs-symbol">:tracks</span>, <span class="hljs-symbol">through:</span> <span class="hljs-symbol">:albums</span>
<span class="hljs-keyword">end</span>
The other end of the association needs to link back:
<span class="hljs-keyword">class</span> <span class="hljs-title class_">Track</span> < <span class="hljs-title class_ inherited__">ApplicationRecord</span>
belongs_to <span class="hljs-symbol">:album</span>
belongs_to <span class="hljs-symbol">:media_type</span>
belongs_to <span class="hljs-symbol">:genre</span>
has_and_belongs_to_many <span class="hljs-symbol">:playlists</span>
has_many <span class="hljs-symbol">:artists</span>, <span class="hljs-symbol">through:</span> <span class="hljs-symbol">:album</span>
<span class="hljs-keyword">end</span>
Unlock Revisiting Ruby on Rails
Subscribe for full access to every course, or buy this one on its own.