I have the following database schema model for a Jukebox:
Artist
has_many :albums
has_many :tracks, through: :albums
Album
belongs_to :artist
has_many :tracks
Track
belongs_to :album
has_one :artist, through: :album
belongs_to :genre
Genre
has_many :tracks
has_many :albums, through: :tracks
has_many :artists, through: :albums
I want to be able to call .albums
on an instance of the Genre
class and return
an array with one instance of each of the albums that has tracks with the associated genre_id
.
What I'm getting is an array with duplicates of the same album instance for each track. E.G. if there are 10,000 tracks with the genre_id
associated to "Rock", I'm going to get an array with 10,000 instances when calling .album
, even if there's only 1000 unique albums within that array.
I'm trying to solve this for a challenge, so just running .all.uniq
on the call won't be sufficient. I need to have something inside the class itself that will return the desired result when .all
is run.
However, I can't find the ActiveRecord command that would essentially filter out the duplicates, and trying to write a separate class method doesn't seem to work either.
Disclosure - I've only been working with ActiveRecord for a few days. I hope the above is clear. Any help much appreciated!
CodePudding user response:
distinct
should work for you:
genre = Genre.first
genre.albums.distinct
CodePudding user response:
Ahh - I eventually found the answer, thanks to this article: https://www.lugolabs.com/articles/distinct-active-records-in-has_many-through-associations
class Genre < ActiveRecord::Base
has_many :tracks
has_many :albums, -> { distinct }, through: :tracks
has_many :artists, -> { distinct }, through: :albums
end