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

Collect all values for a given column in an ActiveRecord scope

The Edge Rider gem Archive 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 Archive 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.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Avatar
Arne Hartherz
Last edit:
about 3 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