Toshimaru's Blog

Select unique values from a column in ActiveRecord

IF you want to select unique values from a column in ActiveRecord, you can use distinct + pluck.

Model.distinct.pluck(:column)

For example:

User.distinct.pluck(:id)
#    (0.1ms)  SELECT DISTINCT "users"."id" FROM "users"

You can also get unique values from multiple columns.

User.distinct.pluck(:id, :name)
#    (0.1ms)  SELECT DISTINCT "users"."id", "users"."name" FROM "users"

See also