Rails 6 adds ActiveRecord::Relation#pick

Prathamesh Sonpatki

By Prathamesh Sonpatki

on January 16, 2019

Before Rails 6, selecting only the first value for a column from a set of records was cumbersome. Let's say we want only the first name from all the posts with category "Rails 6".

1>> Post.where(category: "Rails 6").limit(1).pluck(:name).first
2   SELECT "posts"."name"
3   FROM "posts"
4   WHERE "posts"."category" = ?
5   LIMIT ?  [["category", "Rails 6"], ["LIMIT", 1]]
6=> "Rails 6 introduces awesome shiny features!"

In Rails 6, the new ActiveRecord::Relation#pick method has been added which provides a shortcut to select the first value.

1>> Post.where(category: "Rails 6").pick(:name)
2   SELECT "posts"."name"
3   FROM "posts"
4   WHERE "posts"."category" = ?
5   LIMIT ?  [["category", "Rails 6"], ["LIMIT", 1]]
6=> "Rails 6 introduces awesome shiny features!"

This method internally applies limit(1) on the relation before picking up the first value. So it is useful when the relation is already reduced to a single row.

It can also select values for multiple columns.

1>> Post.where(category: "Rails 6").pick(:name, :author)
2   SELECT "posts"."name", "posts"."author"
3   FROM "posts"
4   WHERE "posts"."category" = ?
5   LIMIT ?  [["category", "Rails 6"], ["LIMIT", 1]]
6=> ["Rails 6.0 new features", "prathamesh"]

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.