instance method
pluck
Ruby on Rails 8.1.2
Since v3.2.22.5Signature
pluck(*column_names)
Use #pluck as a shortcut to select one or more attributes without loading an entire record object per row.
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] Comment.joins(:person).pluck(:id, person: :id) # SELECT comments.id, person.id FROM comments INNER JOIN people person ON person.id = comments.person_id # => [[1, 2], [2, 2]] Comment.joins(:person).pluck(:id, person: [:id, :name]) # SELECT comments.id, person.id, person.name FROM comments INNER JOIN people person ON person.id = comments.person_id # => [[1, 2, 'David'], [2, 2, 'David']] Person.pluck(Arel.sql('DATEDIFF(updated_at, created_at)')) # SELECT DATEDIFF(updated_at, created_at) FROM people # => ['0', '27761', '173']
Be aware that #pluck ignores any previous select clauses
Person.select(:name).pluck(:id) # SELECT people.id FROM people
See also #ids.
Parameters
-
column_namesrest
Source
# File activerecord/lib/active_record/relation/calculations.rb, line 295
def pluck(*column_names)
if @none
if @async
return Promise::Complete.new([])
else
return []
end
end
if loaded? && all_attributes?(column_names)
result = records.pluck(*column_names)
if @async
return Promise::Complete.new(result)
else
return result
end
end
if has_include?(column_names.first)
relation = apply_join_dependency
relation.pluck(*column_names)
else
model.disallow_raw_sql!(flattened_args(column_names))
relation = spawn
columns = relation.arel_columns(column_names)
relation.select_values = columns
result = skip_query_cache_if_necessary do
if where_clause.contradiction? && !possible_aggregation?(column_names)
ActiveRecord::Result.empty(async: @async)
else
model.with_connection do |c|
c.select_all(relation.arel, "#{model.name} Pluck", async: @async)
end
end
end
result.then do |result|
type_cast_pluck_values(result, columns)
end
end
end
Defined in activerecord/lib/active_record/relation/calculations.rb line 295
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveRecord::Calculations