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

0

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.