在我的应用程序中,我需要显示一个歌曲列表。现在我正在做这件事:
Song.all.sort {|x,y| x.artist.name <=> y.artist.name }不幸的是,这意味着“臭名昭著的B.I.G”将与T排序,而我希望他与N排序(即,为了排序的目的,我想忽略冠词-- " the“、"a”和"an“。
我的第一个想法是这样做:
Song.all.sort {|x,y| x.artist.name.gsub(/^(the|a|an) /i, '') <=> y.artist.name.gsub(/^(the|a|an) /i, '') }但它似乎不起作用。有什么想法?
发布于 2009-09-10 01:28:18
我最喜欢的解决此类问题的方法是在数据库中存储一个extra sort_order列。
这样,当您有10000首想要翻页的歌曲时,您可以在SQL中执行此操作,而不必将它们全部拉回。
添加一个before_save筛选器来保持该列的同步非常简单。
无需模式更改的干净解决方案是:
class Artist
def sortable_name
self.name.sub(/^(the|a|an)\s+/i, '')
end
end
class Song
def sortable_name
# note the - is there so [Radio] [head on] and [Radiohead] [karma police]
# are not mixed in the ordering
"#{artist.sortable_name} - #{name}"
end
end
# breaks ties as well
Song.all.sort_by { |song| song.sortable_name }https://stackoverflow.com/questions/1402915
复制相似问题