1

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).

Community
  • 1
  • 1
Dan Tappin
  • 2,692
  • 3
  • 37
  • 77

1 Answers1

3

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)
Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145