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".
>> 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"]
If this blog was helpful, check out our full blog archive.