【问题标题】:How to get the unique values in nested 2d array based on specific index in ruby [duplicate]如何根据ruby中的特定索引获取嵌套二维数组中的唯一值[重复]
【发布时间】:2024-01-19 20:35:01
【问题描述】:

如何根据二维数组的特定索引获取唯一的二维嵌套数组?

基本上,我想在下拉列表中显示属于某个关联模型的唯一名称。这是查询的样子

Product.where(live: true).includes(:primary_concern).map{|q| [q.primary_concern.name, q.id]}

但它会返回所有名称,而我只想在下拉列表中显示唯一名称。

我尝试使用 rails group by,但它抛出未定义的表错误,因为 primary_concern 本身不是模型,它与模型的关联让我们说 关注,使用不同的 foerign_key 名称

【问题讨论】:

  • 可以展示模型吗?
  • 是的,uniq(&:first) 是我正在寻找的。谢谢

标签: arrays ruby group-by ruby-on-rails-5 unique-constraint


【解决方案1】:

这应该可行:

Product.where(live: true).includes(:primary_concern).map{|q| [q.primary_concern.name, q.id]}.uniq(&:first)

【讨论】: