How can I include ordering in an ‘order’ ActiveRelation call that’s more than one level deep?
That is, I understand the answer when it’s only one level deep (asked and answered at Rails order by associated data). However, I have a case where the data on which I want to sort is two levels deep.
Specifically, in my schema a SongbookEntry contains a Recording, which contains an Artist and a Song. I want to be able to sort SongbookEntry lists by song title.
I can go one level deep and sort Recordings by song title:
@recordings = Recording.includes(:song).order('songs.title')
…but don’t know how to go two levels deep. In addition, it would be great if I could sort on the recording (that is, the song title and the artist name) — is this possible without descending into SQL?
Thanks for any help,
Keith
If you model the association between
SongbookEntryandSongas such:you will be able to access
@songbookentry.songandSongbookEntry.joins(:song)using your existing schema.Edit:
Applying the same idea for
Artist, a possible query would be:Note that this may not be the most efficient operation (multiple joins involved) even though it looks Rails-ish, so later on you may want to denormalize the tables as Ryan suggested, or find another way to model the data.