Method: ActiveRecord::Calculations#pluck
- Defined in:
- activerecord/lib/active_record/relation/calculations.rb
#pluck(*column_names) ⇒ Object
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']
See also #ids.
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 |
# File 'activerecord/lib/active_record/relation/calculations.rb', line 291 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? 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 |