Collect all values for a given column in an ActiveRecord scope
Theallows you to collect an array of values for one field of your ActiveRecord elements:
>> User.active.collect_column(:id) => [1, 5, 23, 42]
It also comes with a
:distinct option in case you are only interested in unique values:
>> Article.collect_column(:state, distinct: true) => ['draft', 'published']
In modern Railses (since 3.2) you can also use ActiveRecord'smethod.
>> User.active.pluck(:id) => [1, 5, 23, 42]
DISTINCT selection, use
distinct for rails 5+) on your scope (not the resulting array).
>> Article.uniq.pluck(:state) # SELECT DISTINCT state FROM articles => ['draft', 'published'] # rails 5+ >> Article.distinct.pluck(:state)
pluck, if available.