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:

>> => [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's pluck method.

>> => [1, 5, 23, 42]

For a DISTINCT selection, use uniq (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)

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:

Arne Hartherz
Last edit:
about 2 years ago
by Daniel Straßner
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