Skip to content

Commit 80cc0d3

Browse files
author
David Heinemeier Hansson
authored
Add Relation#pick as short-hand for single-value plucks (rails#31941)
* Add Relation#pick as short-hand for single-value plucks
1 parent b6ee4e4 commit 80cc0d3

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

activerecord/lib/active_record/relation/calculations.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,24 @@ def pluck(*column_names)
200200
end
201201
end
202202

203+
# Pick the value(s) from the named column(s) in the current relation.
204+
# This is short-hand for `relation.limit(1).pluck(*column_names).first`, and is primarily useful
205+
# when you have a relation that's already narrowed down to a single row.
206+
#
207+
# Just like #pluck, #pick will only load the actual value, not the entire record object, so it's also
208+
# more efficient. The value is, again like with pluck, typecast by the column type.
209+
#
210+
# Person.where(id: 1).pick(:name)
211+
# # SELECT people.name FROM people WHERE id = 1 LIMIT 1
212+
# # => 'David'
213+
#
214+
# Person.where(id: 1).pick(:name, :email_address)
215+
# # SELECT people.name, people.email_address FROM people WHERE id = 1 LIMIT 1
216+
# # => [ 'David', 'david@loudthinking.com' ]
217+
def pick(*column_names)
218+
limit(1).pluck(*column_names).first
219+
end
220+
203221
# Pluck all the ID's for the relation using the table's primary key
204222
#
205223
# Person.ids # SELECT people.id FROM people

activerecord/test/cases/calculations_test.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -793,6 +793,16 @@ def test_pluck_loaded_relation_sql_fragment
793793
end
794794
end
795795

796+
def test_pick_one
797+
assert_equal "The First Topic", Topic.order(:id).pick(:heading)
798+
assert_nil Topic.where("1=0").pick(:heading)
799+
end
800+
801+
def test_pick_two
802+
assert_equal ["David", "david@loudthinking.com"], Topic.order(:id).pick(:author_name, :author_email_address)
803+
assert_nil Topic.where("1=0").pick(:author_name, :author_email_address)
804+
end
805+
796806
def test_grouped_calculation_with_polymorphic_relation
797807
part = ShipPart.create!(name: "has trinket")
798808
part.trinkets.create!

0 commit comments

Comments
 (0)