Essential productivity shortcuts, memory optimization patterns, and debugging tricks for daily Rails engineering.
Query & Memory Optimizations
1. pluck vs map
pluck queries database columns directly without instantiating ActiveRecord Ruby model objects:
# SLOW: Instantiates 10,000 User objects in memory
User.all.map(&:email)
# FAST: Selects only the email column into an array of strings
User.pluck(:email)
2. Batch Processing with find_each
Avoid loading huge tables into memory at once:
# Loads in batches of 1,000 records
User.find_each(batch_size: 1000) do |user|
user.sync_with_crm
end
Console Productivity Shortcuts
# Access the result of the last evaluated expression
user = User.find(1)
_ # Returns the user object
# Benchmark execution time in console
Benchmark.ms { 1000.times { User.count } }
# Reload Rails application code without restarting console
reload!
Touching Timestamps
Update a parent model's updated_at timestamp whenever a child association updates:
class Comment < ApplicationRecord
belongs_to :article, touch: true
end