Search code examples
arraysrubygroup-byruby-on-rails-5unique-constraint

How to get the unique values in nested 2d array based on specific index in ruby


How can I get a unique 2d nested array based on a specific index of that 2d array?

Basically, I want to show the unique names that belong to a certain associated model, in the dropdown list. Here is what the query looks like

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

but it returns all the names while I want only unique names to show in the dropdown list.

I tried to use rails group by, but it is throwing undefined table error because primary_concern is not a model itself, its an association to a model let say concern, with a different foerign_key name


Solution

  • This should work:

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