Read more

Collect all values for a given column in an ActiveRecord scope

Arne Hartherz
September 13, 2010Software engineer at makandra GmbH

In modern Rails versions you can also use ActiveRecord's pluck Show archive.org snapshot method.

>> User.active.pluck(:id)
=> [1, 5, 23, 42]
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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

>> User.active.ids
=> [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 Show archive.org snapshot for the same purpose as pluck.

Posted by Arne Hartherz to makandra dev (2010-09-13 19:57)