Posted about 10 years ago. Visible to the public. Repeats.

Collect all values for a given column in an ActiveRecord scope

The Edge Rider gem allows you to collect an array of values for one field of your ActiveRecord elements:

Copy
>> 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:

Copy
>> Article.collect_column(:state, distinct: true) => ['draft', 'published']

In modern Railses (since 3.2) you can also use ActiveRecord's pluck method.

Copy
>> User.active.pluck(:id) => [1, 5, 23, 42]

For a DISTINCT selection, use uniq (distinct for rails 5+) on your scope (not the resulting array).

Copy
>> Article.uniq.pluck(:state) # SELECT DISTINCT state FROM articles => ['draft', 'published'] # rails 5+ >> Article.distinct.pluck(:state)

EdgeRider delegates collect_column to pluck, if available.

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Avatar
Arne Hartherz
Last edit:
about 2 years ago
by Daniel Straßner
Keywords:
column, single, columns
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more