Collect all values for a given column in an ActiveRecord scope

Updated . Posted . Visible to the public.

In modern Rails versions you can also use ActiveRecord's pluck Show snapshot 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).

# SELECT DISTINCT state FROM articles
=> ['draft', 'published']

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

# 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 Show snapshot for the same purpose as pluck.

Arne Hartherz
Last edit
Felix Eschey
column, single, columns
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2010-09-13 17:57)