Dan
Dan

Reputation: 2319

Rails Get All Uniques in Column of Arrays

So here is my scenario.

I have a column in my table called categories and it holds an array. Each array value is a different category. I am looking for a way to get all unique categories in the table.

When I use this code

Products.uniq.pluck(:categories)

It returns a collection of all the unique combinations of arrays so i need to take it a step further and get all the unique array values. Looking for an efficient way of doing that. Hope that all makes sense.

Upvotes: 0

Views: 33

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118261

As .pluck gives you an array of array. You need to flatten it and then run uniq operations.

Products.pluck(:categories).flatten.uniq

Upvotes: 2

Related Questions