/ RAILS

Rails 6 introduces ActiveRecord::Relation#pick method

Rails 6 adds ActiveRecord::Relation pick method to select values of columns from the first record matching where conditions. This is a shorthand for plucking column names, limiting records and then finding first value for the matching criteria.

Let’s take an example.

# id
# name
# email
# created_at
# updated_at
class User < ApplicationRecord
end

Now, to find out the name of user with email [email protected], before Rails 6 we will get it done as given below.

Before Rails 6

User.where(email: '[email protected]').limit(1).pluck(:name).first
# (0.7ms)  SELECT  "users"."name" FROM "users" WHERE "users"."email" = $1 LIMIT $2  [["email", "[email protected]"], ["LIMIT", 1]]
# => Akshay

After Rails 6

With addition of ActiveRecord::Relation#pick, the same result can be obtained with code given below.

User.where(email: '[email protected]').pick(:name)
# (0.7ms)  SELECT  "users"."name" FROM "users" WHERE "users"."email" = $1 LIMIT $2  [["email", "[email protected]"], ["LIMIT", 1]]
# => Akshay

As we can see, the result is same. Thus, we can use pick on ActiveRecord::Relation to select values of one or more columns of the first record matching where conditions.

Backport ActiveRecord::Relation#pick

In order to use ActiveRecord::Relation#pick with Rails 4.2 or Rails 5 applications, we can use the gem activerecord-pick. Just add the gem to Gemfile as,

gem 'activerecord-pick'

And then you are ready to use ActiveRecord::Relation#pick.

References

akshay

Akshay Mohite

Hi there! I am a Ruby on Rails & ReactJS Enthusiast, building some cool products at DTree Labs.

Read More
Buy me a coffee