In an earlier post, we explained the addition and usage of ActiveRecord::Relation#pick
method. In essence, ActiveRecord::Relation#pick
allows picking the first value from the named column in the relation.
Taking forward the implementation, Rails has added a change that allows ActiveRecord::Relation#pick
to use already loaded results. Before the change, it used to make a query to the database even when the results were already loaded. This change is along the same lines of ActiveRecord#pluck
implementation, where it uses already loaded results when available.
In Rails 6
books = Book.where(published: true).order(:published_at).limit(5).load
# SELECT "books".* FROM "books"
# WHERE "books"."published" = $1
# ORDER BY "books"."published_at" ASC LIMIT $2 [["published", "t"], ["LIMIT", 5]]
books.pick(:name) # Makes query to the database even when results are loaded
# SELECT "books"."name" FROM "books" WHERE "books"."published" = $1
# ORDER BY "books"."published_at" ASC LIMIT $2 [["published", "t"], ["LIMIT", 1]]
=> "Data Communication and Networking"
In Rails 6.1
books = Book.where(published: true).order(:published_at).limit(5).load
# SELECT "books".* FROM "books"
# WHERE "books"."published" = $1
# ORDER BY "books"."published_at" ASC LIMIT $2 [["published", "t"], ["LIMIT", 5]]
books.pick(:name) # No query to the database when results are loaded
=> "Data Communication and Networking"
Summary
This change is pretty useful as we do not need to worry about extra queries being made to the database while using ActiveRecord::Relation#pick
with already loaded results.