To retrieve unique values from a column in ActiveRecord, the distinct
method combined with pluck
can be utilized.
Model.distinct.pluck(:column)
For instance:
User.distinct.pluck(:id)
# (0.1ms) SELECT DISTINCT "users"."id" FROM "users"
This approach can also be extended to obtain unique values from multiple columns.
User.distinct.pluck(:id, :name)
# (0.1ms) SELECT DISTINCT "users"."id", "users"."name" FROM "users"
API Document
ActiveRecord::Calculations | RailsDoc(β)
Person.distinct.pluck(:role) # SELECT DISTINCT role FROM people # => ['admin', 'member', 'guest']