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".
>> Post.where(category: "Rails 6").limit(1).pluck(:name).first
SELECT "posts"."name"
FROM "posts"
WHERE "posts"."category" = ?
LIMIT ? [["category", "Rails 6"], ["LIMIT", 1]]
=> "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.
>> Post.where(category: "Rails 6").pick(:name)
SELECT "posts"."name"
FROM "posts"
WHERE "posts"."category" = ?
LIMIT ? [["category", "Rails 6"], ["LIMIT", 1]]
=> "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.
>> Post.where(category: "Rails 6").pick(:name, :author)
SELECT "posts"."name", "posts"."author"
FROM "posts"
WHERE "posts"."category" = ?
LIMIT ? [["category", "Rails 6"], ["LIMIT", 1]]
=> ["Rails 6.0 new features", "prathamesh"]

Written byPrathamesh Sonpatki
Related blogs
- 01Rails 6 adds support to persist timezones of Active JobSeptember 1, 2020 · Chetan Gawai
- 02Rails 6 adds including & excluding method on EnumerablesAugust 18, 2020 · Akhil Gautam
- 03Rails 6 fixes after_commit callback invocation bugFebruary 25, 2020 · Amit Choudhary
- 04Rails 6 adds rails db:prepare to migrate or setup a databaseDecember 10, 2019 · Akhil Gautam