What the Pluck?

A look at the ActiveRecord method

Mary Kang
3 min readApr 16, 2020

Pluck is an ActiveRecord query method that returns values as an Array from desired attributes without loading and looking through the entire collection.

Pupper.pluck(:name)
What are all the puppers’ names?

How exactly does a Pluck pluck?

Pluck accepts a list of table column names as arguments. It looks in the database, goes to the table, finds the specified columns, looks to the associated values, and finally, returns those values as an Array.

See the following SQL table:

The SQL table
shows the SQL query that runs when pluck is used

Above, we use the pluck method to select just the puppers’ names from the table. This generates the following SQL query:

                SELECT "puppers"."name" FROM "puppers"

which then returns the array of all the puppers’ names:

           ["Leo", "Zeus", "Dylan", "George", "Falafel"]

Why Pluck?

Pluck is more efficient than looking through an entire collection and mapping over it to get the attribute data you want.

Since pluck returns a Ruby Array as opposed to an ActiveRecordobject, using it could result in improved performance in querying.

Instead of writing:

               Pupper.select(:name).map {|p| p.name}

or

                  Pupper.select(:name).map(&:name)

you can simply write

                         Pupper.pluck(:name)
Leo approves!

Can we see some Pluck?

Pluck returns an array of attribute values that correspond to the given column name.

Pupper.pluck(:name)
# SELECT "puppers"."name" FROM "puppers"
# => ["Leo", "Zeus", "Dylan", "George", "Falafel"]

Pluck can be passed multiple attributes at a time.

Pupper.pluck(:name, :breed)
# SELECT "puppers"."name", "puppers"."breed" FROM "puppers"
# => ["Leo", "Cockapoo"], ["Zeus", "Bichon Frise"], ["Dylan", "Spaniel"], ["George", "Lab Mix"], ["Falafel", "Golden Retriever"]]

Pluck can be used at the end of a chain.

Pupper.distinct.pluck(:phrase)
#
SELECT DISTINCT "puppers"."phrase" FROM "puppers"
# => ["13/10 would pet", "Always Yappy hour", "Boop the Snoot", "You are doing me a frighten"]

another example:

Pupper.where(age: 14).pluck(:name)
# SELECT "puppers"."name" FROM "puppers" WHERE "puppers"."age" = ?
[["age", "14"]]
# => ["Leo"]
Yes, Leo knows he aged very very well.

Check out the Rails guides for more information on this fun method.

Whether this was a new discovery for you or a just a quick refresher, I hopeplucking and pictures of Leo bring you as much as joy as they do for me!

--

--