Dan Tappin
Dan Tappin

Reputation: 3032

Unique values from array in column

This post is close:

Rails: select unique values from a column

Model.uniq.pluck(:rating)

works great except in my case my column has an array in it so I get something like this:

[["guest"], ["engineer", "manager"], ["engineer"], ["admin"], ["operations"], ["operator"], ["operator", "manager"]]

I would like these reduced down to the simplest list (in alphabetical order while we are at it).

Upvotes: 1

Views: 126

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52357

What you need is Array#flatten and Array#sort

Model.pluck(:rating).flatten
#=>["guest", "engineer", "manager", "engineer", "admin", "operations", "operator", "operator", "manager"]

Now sort it:

Model.pluck(:rating).flatten.uniq
#= ["guest", "engineer", "manager", "admin", "operations", "operator"]

Model.pluck(:rating).flatten.uniq.sort
#=> ["admin", "engineer", "guest", "manager", "operations", "operator"]

If there could be uppercase words, downcase them while sorting, to make sure sorting is case insensitive:

Model.pluck(:rating).flatten.uniq.sort_by(&:downcase)

Upvotes: 3

Related Questions