Performance: Select and pluck
This affects how efficiently data is fetched from the database and how much data is sent to the app, impacting page load speed and server response time.
User.pluck(:name)
User.select(:id, :name).map(&:name)| Pattern | Data Fetched | Server Processing | Network Payload | Verdict |
|---|---|---|---|---|
| select + map | AR objects with selected columns | High (object creation) | Large | [X] Bad |
| pluck | Only requested columns | Low (direct array) | Small | [OK] Good |
select and pluck in Rails ActiveRecord?select behaviorselect loads model objects but only with the specified columns, so you still get ActiveRecord objects.pluck behaviorpluck fetches column values directly from the database and returns them as a simple array, not objects.select returns model objects with selected columns, pluck returns an array of values. -> Option Bpluck?pluck is called on the model with the column symbol as argument, like User.pluck(:email).users = User.select(:id, :name).where(active: true) names = users.pluck(:name)
User.select(:id, :name).where(active: true) returns ActiveRecord objects with only id and name for active users.pluck(:name) on this relation fetches the name column values directly from the database for active users.users = User.pluck(:id, :name).select { |u| u.active? }pluck(:id, :name) returns an array of arrays like [[1, "Alice"], [2, "Bob"]], not User objects.active?active? method on them causes a NoMethodError.active? on array elements causes error -> Option Dselect then maps emails, which loads more data than needed.where to filter active users, then pluck to get emails directly from DB, then uniq to remove duplicates efficiently.pluck returns array, so where after pluck causes error.Pass the test and this pattern moves unknown