在我的应用程序中,我需要显示歌曲列表。现在我正在这样做:
Song.all.sort {|x,y| x.artist.name <=> y.artist.name }
不幸的是,这意味着“The Notorious 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, '') }
但这似乎不起作用。想法?
解决此类问题我最喜欢的方法是存储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 }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)