ActiveRecord querying: pluck/select
This course covers how ActiveRecord's .pluck and related methods choose which columns load. It starts with .pick, which adds LIMIT 1 and returns a single value. It compares the query cost of .pluck and .map(&:attr) on loaded and unloaded relations. It shows .pluck across a join, how a join multiplies rows, and how .distinct removes duplicates in SQL. It explains why .pluck ends a query chain, how it skips the Translatable locale fallback on JSONB columns, and how the app plucks ids into a Set for fast lookups.
What you'll learn
- ✓Using .pick to fetch one value with LIMIT 1
- ✓When .pluck costs a query compared with .map(&:attr)
- ✓Plucking columns from a joined table and removing duplicates with .distinct
- ✓Why .pluck has to be the last call in a query chain
- ✓How .pluck skips the Translatable locale fallback on JSONB columns
- ✓Plucking foreign-key ids into a Set for fast membership checks
.pick: the single-row shortcut of .pluck
The lesson "SELECT & FROM in Rails", in Raw SQL: select & from, covered the basics. .select(:name, :email) returns model objects with only the chosen columns filled in, and an unselected column reads back nil, which looks the same as a database NULL. .pluck(:name) skips building models and returns…
Read the full lesson free →Curriculum
7 lessons.pick: the single-row shortcut of .pluck
.pick returns one value with LIMIT 1 in the SQL, while .pluck.first fetches every matching row first.
.pluck vs .map(&:attr): what costs a query
.pluck narrows the SELECT on unloaded relations, reads memory on loaded ones, and always queries for SQL expressions.
.pluck across a join
A qualified string like "lessons.title" plucks a joined table's column, and the INNER JOIN returns one row per lesson.
distinct.pluck: removing duplicates from a plucked column
Calling .distinct before .pluck adds DISTINCT to the SQL, while calling it afterward raises NoMethodError on the array.
.pluck ends the chain: it returns an array
.pluck returns a plain Array, so every .where, .joins and .order has to come before it.
The Translatable trap: .pluck skips the locale fallback
.pluck reads Translatable JSONB columns as raw hashes and skips the I18n.locale fallback that the title method runs.
Putting it together: pluck for IDs, not just display
The app's progress queries pluck foreign-key ids and convert them with .to_set for O(1) membership checks.