1

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

2
  • Can you show the models? Commented May 16, 2021 at 15:58
  • 1
    Yes, uniq(&:first) is what I am looking for. Thanks Commented May 22, 2021 at 19:54

1 Answer 1

1

This should work:

Product.where(live: true).includes(:primary_concern).map{|q| [q.primary_concern.name, q.id]}.uniq(&:first)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.