Ruby On Rails Code Optimization Shortcuts
βοΈ Level Up Your Ruby on Rails Game: 10+ Code Optimization Shortcuts Only Pros Use ππ‘
Ruby on Rails is elegant by default, but the real magic happens when you know its hidden shortcuts and smart optimizations. If youβre still writing verbose, repetitive code β youβre doing it wrong. π
Hereβs your cheat sheet to code smarter, cleaner, and faster using these pro-level Rails tricks β optimized for performance, readability, and development speed. π»β‘
π§ 1. select
Only the Columns You Need (Avoid SELECT *
)
User.select(:id, :email).where(active: true)
π Why: Avoids loading unnecessary data into memory β faster DB queries and lighter memory footprint.
β
Pro Tip:
Combine with .find_each
to process large records efficiently:
User.select(:id, :email).find_each(batch_size: 500) do |user|
# process user
end
β‘ 2. pluck
Over .map(&:field)
= Ultra-Fast Fetch
User.pluck(:email)
π§ Why: Direct SQL SELECT β skips ActiveRecord object creation = faster execution!
β Avoid this:
User.all.map(&:email) # Slow & memory heavy
β Pro Tip:
User.where(active: true).pluck(:id, :email)
π§ββοΈ 3. find_by
Over where(...).first
User.find_by(email: "demo@example.com")
π₯ Why: Less verbose, more intention-revealing, optimized under the hood for early exit.
π§© 4. Memoization Pattern for Heavy Methods
def user_profile
@user_profile ||= fetch_profile_from_api
end
βοΈ Why: Avoids repeated expensive calls. Elegant state caching pattern for instance methods.
β Pro Tip: Use for:
- API responses
- DB-intensive lookups
- File reads
π§Ό 5. Service Objects + yield_self
class InvoiceGenerator
def self.call(order)
order.yield_self do |o|
# process invoice
end
end
end
π Why: Keeps business logic clean, separates concerns, and improves testability.
β Pro Tip: Chain-friendly and readable for complex service pipelines.
π 6. scope
for Reusable, Chainable Queries
scope :active, -> { where(active: true) }
scope :recent, -> { order(created_at: :desc) }
π Why: Clean and DRY code. Chaining becomes beautiful:
User.active.recent.limit(10)
π 7. before_save if:
Condition for Lean Callbacks
before_save :normalize_email, if: -> { email_changed? }
def normalize_email
self.email = email.strip.downcase
end
β οΈ Why: Avoid running unnecessary code β optimize only when needed.
β
Pro Tip:
Use conditional callbacks (if
, unless
) instead of burying checks inside methods.
π 8. update_columns
vs update
vs update_attribute
user.update_columns(views_count: user.views_count + 1)
β update
runs validations and callbacks.
β
update_columns
skips validations, callbacks β use only when safe.
π When to use:
- Updating counters/logs
- System-generated updates
𧬠9. JSON Column Access via store_accessor
store_accessor :preferences, :theme, :notifications_enabled
π― Why: Access JSON fields like normal attributes β reduces boilerplate!
user.theme # => "dark"
user.notifications_enabled = true
π 10. Rails Console Ninja Moves
app.get '/dashboard'
app.response.body
π±βπ€ Why:
Use the app
object in console to simulate real HTTP requests.
β
Pro Tip:
Use .helpers
, .url_helpers
, and .reload!
like a pro:
helpers.number_to_currency(12345.67)
Rails.application.routes.url_helpers.user_path(1)
reload!
π Bonus: Optimize Seeds with find_or_create_by
User.find_or_create_by(email: 'admin@example.com') do |u|
u.name = 'Admin'
u.role = 'superadmin'
end
π₯ Why: Avoid duplicate records and make your seed idempotent (safe to run multiple times).
β¨ Final Pro Tips
β
Use .includes
or .eager_load
to prevent N+1 queries
β
Prefer delegate
for cleaner model relationships
β
Cache partials or fragments with cache
helper
β
Use bullet
gem in dev to catch performance issues
β
Profile slow SQL queries using rails db:verbose
and EXPLAIN
π Conclusion
You donβt need to write more code β you need to write optimized code. Rails gives you everything, but itβs up to you to use its power features wisely. β¨
These shortcuts arenβt just tricks β theyβre a philosophy:
βWrite less. Do more. Stay fast. Stay elegant.β
© Lakhveer Singh Rajput - Blogs. All Rights Reserved.