Skip to content

Commit ea50d53

Browse files
committed
Expand and improve #pluck docs
1 parent 3f352d0 commit ea50d53

File tree

1 file changed

+27
-6
lines changed

1 file changed

+27
-6
lines changed

activerecord/lib/active_record/relation/calculations.rb

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -108,15 +108,36 @@ def calculate(operation, column_name, options = {})
108108
0
109109
end
110110

111-
# This method is designed to perform select by a single column as direct SQL query
112-
# Returns <tt>Array</tt> with values of the specified column name
113-
# The values has same data type as column.
111+
# Use <tt>pluck</tt> as a shortcut to select a single attribute without
112+
# loading a bunch of records just to grab one attribute you want.
113+
#
114+
# Person.pluck(:name)
115+
#
116+
# instead of
117+
#
118+
# Person.all.map(&:name)
119+
#
120+
# Pluck returns an <tt>Array</tt> of attribute values type-casted to match
121+
# the plucked column name, if it can be deduced. Plucking a SQL fragment
122+
# returns String values by default.
114123
#
115124
# Examples:
116125
#
117-
# Person.pluck(:id) # SELECT people.id FROM people
118-
# Person.uniq.pluck(:role) # SELECT DISTINCT role FROM people
119-
# Person.where(:age => 21).limit(5).pluck(:id) # SELECT people.id FROM people WHERE people.age = 21 LIMIT 5
126+
# Person.pluck(:id)
127+
# # SELECT people.id FROM people
128+
# # => [1, 2, 3]
129+
#
130+
# Person.uniq.pluck(:role)
131+
# # SELECT DISTINCT role FROM people
132+
# # => ['admin', 'member', 'guest']
133+
#
134+
# Person.where(:age => 21).limit(5).pluck(:id)
135+
# # SELECT people.id FROM people WHERE people.age = 21 LIMIT 5
136+
# # => [2, 3]
137+
#
138+
# Person.pluck('DATEDIFF(updated_at, created_at)')
139+
# # SELECT DATEDIFF(updated_at, created_at) FROM people
140+
# # => ['0', '27761', '173']
120141
#
121142
def pluck(column_name)
122143
key = column_name.to_s.split('.', 2).last

0 commit comments

Comments
 (0)