How to Use pluck in Rails: Quick Guide and Examples
In Rails, use
pluck to quickly get an array of values for one or more columns directly from the database without loading full ActiveRecord objects. For example, User.pluck(:name) returns an array of all user names.Syntax
The pluck method is called on an ActiveRecord relation or model and takes one or more column names as arguments. It returns an array of values for those columns directly from the database.
Model.pluck(:column)- returns an array of values for one column.Model.pluck(:col1, :col2)- returns an array of arrays with values for multiple columns.
ruby
Model.pluck(:column_name) Model.pluck(:column1, :column2)
Example
This example shows how to use pluck to get all user emails and then get both names and emails together.
ruby
class User < ApplicationRecord
# Assume users table has columns :id, :name, :email
end
# Get all user emails
emails = User.pluck(:email)
puts emails.inspect
# Get names and emails as arrays
names_and_emails = User.pluck(:name, :email)
puts names_and_emails.inspectOutput
["alice@example.com", "bob@example.com", "carol@example.com"]
[["Alice", "alice@example.com"], ["Bob", "bob@example.com"], ["Carol", "carol@example.com"]]
Common Pitfalls
Common mistakes when using pluck include:
- Expecting
pluckto return ActiveRecord objects instead of plain arrays. - Using
pluckon unsaved or non-persisted objects (it only works on database queries). - Passing invalid column names, which raises an error.
Always ensure the columns exist and remember pluck skips callbacks and validations because it does not instantiate objects.
ruby
# Wrong: expecting ActiveRecord objects users = User.pluck(:name) users.each do |user| puts user.name # Error: user is a string, not an object end # Right: use pluck for values only names = User.pluck(:name) names.each do |name| puts name # Works fine end
Quick Reference
| Usage | Description | Return Value |
|---|---|---|
| Model.pluck(:column) | Get array of values for one column | Array of values |
| Model.pluck(:col1, :col2) | Get array of arrays for multiple columns | Array of arrays |
| Relation.pluck(:column) | Works on ActiveRecord relations too | Array of values |
| Model.pluck(:invalid_column) | Raises error if column does not exist | Error |
Key Takeaways
Use pluck to fetch specific columns directly from the database as arrays.
Pluck returns plain arrays, not ActiveRecord objects.
It is faster and uses less memory than loading full records.
Ensure column names are valid to avoid errors.
Pluck works on models and query relations.