pluck
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0
- 2.2.1
- 2.3.8
- 3.0.0
- 3.0.9
- 3.1.0
- 3.2.1 (0)
- 3.2.8 (0)
- 3.2.13 (0)
- 4.0.2 (38)
- 4.1.8 (0)
- 4.2.1 (0)
- 4.2.7 (0)
- 4.2.9 (0)
- 5.0.0.1 (1)
- 5.1.7 (0)
- 5.2.3 (0)
- 6.0.0 (0)
- 6.1.3.1 (1)
- 6.1.7.7 (0)
- 7.0.0 (0)
- 7.1.3.2 (-2)
- 7.1.3.4 (0)
- What's this?
pluck(*column_names)
public
Use #pluck as a shortcut to select one or more attributes without loading a bunch of records just to grab the attributes you want.
Person.pluck(:name)
instead of
Person.all.map(&:name)
Pluck returns an Array of attribute values type-casted to match the plucked column names, if they can be deduced. Plucking an SQL fragment returns String values by default.
Person.pluck(:name) # SELECT people.name FROM people # => ['David', 'Jeremy', 'Jose'] Person.pluck(:id, :name) # SELECT people.id, people.name FROM people # => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']] Person.distinct.pluck(:role) # SELECT DISTINCT role FROM people # => ['admin', 'member', 'guest'] Person.where(age: 21).limit(5).pluck(:id) # SELECT people.id FROM people WHERE people.age = 21 LIMIT 5 # => [2, 3] Person.pluck('DATEDIFF(updated_at, created_at)') # SELECT DATEDIFF(updated_at, created_at) FROM people # => ['0', '27761', '173']
See also #ids.
Text improvement
Where it says: without loading a bunch of records should say: without loading a bunch of columns/attributes Considering that record usually is a row.
Text improvement
The statement about not loading a bunch of records is correct because pluck returns an Array of values, not a ActiveRecord::Relation or an Array of Records.
The exact wording though may be:
“…without retrieving from the database unused columns or loading a bunch of records just to grab the attributes you want”