0

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

4

3 回答 3

0

我建议将艺术家姓名(可能还有歌曲名称)存储在录音本身上,这样您就不必“下降到 SQL”。

于 2012-10-29T08:13:17.213 回答
0

如果您对SongbookEntry和之间的关联进行建模Song

class SongbookEntry < ActiveRecord::Base
  # ...
  has_one :song, through: :recording
end

您将能够访问@songbookentry.songSongbookEntry.joins(:song)使用现有架构。

编辑:

对 应用相同的想法Artist,可能的查询是:

SongbookEntry.joins(:song,:artist).order('songs.title','artists.name')

请注意,这可能不是最有效的操作(涉及多个连接),即使它看起来像 Rails 一样,所以稍后您可能希望按照 Ryan 的建议对表进行非规范化,或者找到另一种对数据建模的方法。

于 2012-10-29T08:22:13.267 回答
0

试试这个
  SongbookEntry.includes(:recording=>[:artist,:song]).order('songs.title, Artists.name')

如果您不想在视图中使用关联表字段,则可以使用联接代替包含

于 2012-10-29T08:22:01.247 回答