0
0
Ruby on Railsframework~5 mins

Select and pluck in Ruby on Rails

Choose your learning style9 modes available
Introduction

Select and pluck help you get specific data from your database easily. They let you pick only the parts you need, making your app faster and simpler.

When you want to get only certain columns from a database table.
When you need a list of values from a single column.
When you want to reduce memory by not loading full records.
When you want to prepare data for dropdown menus or reports.
When you want to speed up queries by fetching less data.
Syntax
Ruby on Rails
Model.select(:column1, :column2)
Model.pluck(:column)

select returns ActiveRecord objects with only chosen columns loaded.

pluck returns an array of values directly from the database.

Examples
Gets User records but only loads name and email fields.
Ruby on Rails
User.select(:name, :email)
Returns an array of all user emails, no full records.
Ruby on Rails
User.pluck(:email)
Returns an array of arrays with name and email pairs.
Ruby on Rails
User.pluck(:name, :email)
Sample Program

This example shows how to use select to get user names and emails as objects, and pluck to get just emails as an array.

Ruby on Rails
class User < ApplicationRecord
end

# Assume users table has columns: id, name, email

# Using select
users = User.select(:name, :email)
users.each do |user|
  puts "Name: #{user.name}, Email: #{user.email}"
end

# Using pluck
emails = User.pluck(:email)
emails.each do |email|
  puts "Email: #{email}"
end
OutputSuccess
Important Notes

Use select when you want ActiveRecord objects but fewer columns.

Use pluck when you want simple arrays and faster queries.

Remember, pluck skips model callbacks and validations.

Summary

Select loads specific columns as objects.

Pluck fetches column values directly as arrays.

Both help make your database queries faster and lighter.