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

Collect all values for a given column in an ActiveRecord scope

In modern Rails versions you can also use ActiveRecord's pluck Archive method.

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

If you are plucking from the id column in particular you can also say:

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

For a DISTINCT selection, use distinct on your scope (not the resulting array).

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

In Rails 3 and 4 you must use uniq instead of distinct:

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

Plucking columns in legacy Rails versions

For older Rails versions you can use the collect_column method from Edge Rider Archive for the same purpose as pluck.

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:
11 days ago
by Emanuel De
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