使用带有嵌套记录的uniq_by方法的Rails

时间:2015-04-01 08:50:22

标签: ruby-on-rails ruby activerecord

我有一个嵌套记录的CollectionProxy:

@saved_videos = Video.all.is_saved
@sentences_to_extract = @saved_videos.map(&:sentences)

每个视频都有很多句子,每个句子都有一个关键词,例如

[
  [Video.id: 1, 
    sentences:
      [Sentence.id: 1, keyword: 'hello'],
      [Sentence.id: 2, keyword: 'friend']
    ],
  [Video.id: 2, 
    sentences:
      [Sentence.id: 3, keyword: 'hello'],
      [Sentence.id: 4, keyword: 'mum']
    ]
]

当我尝试:

@sentences_to_extract.uniq_by(&:keyword)

它返回

undefined method `uniq_by' for #<Array:0x000001031f7968> 

使用唯一关键字返回单个句子集合的最佳方法是什么,或者更一般地说,通过特定的唯一属性选择嵌套记录?

1 个答案:

答案 0 :(得分:0)

感谢@ArupRakshit,这已经解决了:我需要将映射的数组展平一个级别,使用flat_map在一个衬里中实现。

工作代码:

Video.all
     .is_saved.flat_map(&:sentences)
     .uniq { |s| s.keyword.downcase }