如何从Ruby on Rails的ActiveRecord has_many关联中提取唯一的值?

2026-04-11 14:411阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计424个文字,预计阅读时间需要2分钟。

如何从Ruby on Rails的ActiveRecord has_many关联中提取唯一的值?

我有以下关联:艺术家 has_many 歌曲。因此,我可以通过以下方式获取艺术家的歌曲:artist.songs。但是,我想只获取歌曲的类型:artist.songs.pluck(:genre)。然而,这种类型可能会在结果中出现多次。

我有以下关联:艺术家has_many歌曲.因此,我可以通过以下方式获得艺术家的歌曲:

artist.songs

但是,我想只获得歌曲的类型:

artist.songs.pluck(:genre)

但是,这种类型可能会在结果中出现多次;我只想获得独特的流派价值观.不幸的是,pluck在这里没有任何帮助,因为它返回一个数组,并且在它上面调用uniq不会调整ActiveRecord查询,而是调用plain Array #uniq.

我可以这样做:

artist.songs.select(:genre).uniq.pluck(:genre)

但我觉得必须有更好的方法.

P.S.:从一些最小的基准测试来看,采用Array#uniq似乎比选择uniq采集要快一些.

如何从Ruby on Rails的ActiveRecord has_many关联中提取唯一的值?

如果使用艺术家的歌曲关联,您​​可以选择不同的流派,然后映射结果以返回字符串:

artist.songs.select('distinct genre').map(&:genre) # or... artist.songs.select(:genre).uniq.map(&:genre) # uniq or distinct work

结果查询:

(0.2ms)SELECT distinct genre FROM“songs”WHERE“songs”.“artist_id”=? [[“artist_id”,1]]

如果在缩小到艺术家的同时直接调用Song模型,您也可以使用uniq:

Song.where(艺术家:艺术家).uniq.pluck(:genre)

结果查询:

(0.2ms)SELECT DISTINCT“songs”.“genre”FROM“songs”WHERE“songs”.“artist_id”= 1

两者都是同等有效的,并且在SQL中执行唯一性操作,而不是在Ruby中.

本文共计424个文字,预计阅读时间需要2分钟。

如何从Ruby on Rails的ActiveRecord has_many关联中提取唯一的值?

我有以下关联:艺术家 has_many 歌曲。因此,我可以通过以下方式获取艺术家的歌曲:artist.songs。但是,我想只获取歌曲的类型:artist.songs.pluck(:genre)。然而,这种类型可能会在结果中出现多次。

我有以下关联:艺术家has_many歌曲.因此,我可以通过以下方式获得艺术家的歌曲:

artist.songs

但是,我想只获得歌曲的类型:

artist.songs.pluck(:genre)

但是,这种类型可能会在结果中出现多次;我只想获得独特的流派价值观.不幸的是,pluck在这里没有任何帮助,因为它返回一个数组,并且在它上面调用uniq不会调整ActiveRecord查询,而是调用plain Array #uniq.

我可以这样做:

artist.songs.select(:genre).uniq.pluck(:genre)

但我觉得必须有更好的方法.

P.S.:从一些最小的基准测试来看,采用Array#uniq似乎比选择uniq采集要快一些.

如何从Ruby on Rails的ActiveRecord has_many关联中提取唯一的值?

如果使用艺术家的歌曲关联,您​​可以选择不同的流派,然后映射结果以返回字符串:

artist.songs.select('distinct genre').map(&:genre) # or... artist.songs.select(:genre).uniq.map(&:genre) # uniq or distinct work

结果查询:

(0.2ms)SELECT distinct genre FROM“songs”WHERE“songs”.“artist_id”=? [[“artist_id”,1]]

如果在缩小到艺术家的同时直接调用Song模型,您也可以使用uniq:

Song.where(艺术家:艺术家).uniq.pluck(:genre)

结果查询:

(0.2ms)SELECT DISTINCT“songs”.“genre”FROM“songs”WHERE“songs”.“artist_id”= 1

两者都是同等有效的,并且在SQL中执行唯一性操作,而不是在Ruby中.