Pluck vs Select in Rails

This article will discuss the differences between select and pluck methods for ActiveRecord in Rails.

Pluck

When pluck is called on a model class, it makes a select query with the name of the column. Let’s say we have a Post model with a title field.

Post.pluck(:title)

It will hit the following query:

SELECT "posts"."title" FROM "posts"

It will then return an array of a string with the value of the column name specified.

=> ["Wisdom", "Wisdom", "Love", "Love", "Life", "Wisdom"]

Select

When select is called on a model class, it makes a select query with the name of the column. Let’s say we have a Post model with a title field.

Post.select(:title)

It will hit the following query:

SELECT "posts"."title" FROM "posts"

Then it will return an ActiveRecord relation Post with just the title field and id field nil.

=> #<ActiveRecord::Relation [#<Post id: nil, title: "Wisdom">, #<Post id: nil, title: "Wisdom">, #<Post id: nil, title: "Love">, #<Post id: nil, title: "Love">, #<Post id: nil, title: "Life">, #<Post id: nil, title: "Wisdom">]>

There you have it - happy plucking and selecting!