Ruby on Rails Secret Methods
π Ruby on Rails Secrets: Hidden Methods That Will Surprise You! πβ¨
Ruby on Rails isnβt just famous for its Convention over Configuration and productivity β it also hides some powerful secret methods π΅οΈββοΈ that many developers donβt discover until years into their career!
Today, Iβm pulling back the curtain to reveal some of these hidden gems, explain them with real-world examples, and share bonus βrecipesβ to make your Rails coding even more magical! π§ββοΈβ¨
Letβs get started! π
1οΈβ£ try
β The Safe Navigator before Safe Navigation
Ever needed to call a method on an object that might be nil
? You probably write:
user && user.name
OR use the safe navigation operator (&.
):
user&.name
But did you know Rails gave you this power before Ruby itself?
user.try(:name)
Example:
user = nil
puts user.try(:name) # => nil (No error!)
Why itβs surprising:
It lets you chain method calls safely even on nil
, long before Ruby added &.
in 2.3.
2οΈβ£ presence
β Cleaner than .blank? ? nil : value
Imagine you check if a string is blank and fallback:
name = user.name
name = nil if name.blank?
Rails shortcut: presence
name = user.name.presence || "Guest"
Example:
"".presence # => nil
"Hello".presence # => "Hello"
Perfect for defaults! π
3οΈβ£ in?
β Readable include?
for Objects
Ever do:
[1, 2, 3].include?(value)
Rails lets you flip it:
value.in? [1, 2, 3]
Example:
1.in? [1, 2, 3] # => true
5.in? [1, 2, 3] # => false
So natural to read! πβ
4οΈβ£ delegate
β One-liner Method Forwarding
Want to forward a method to an associated object? Donβt write manual delegation! Use delegate
.
Example:
class User < ApplicationRecord
has_one :profile
delegate :bio, to: :profile, allow_nil: true
end
user.bio # Calls user.profile.bio
One line, zero boilerplate! β¨
5οΈβ£ tap
+ then
β Chain and Peek
tap
is a Ruby core method, but in Rails it shines with blocks:
tap
lets you do something without breaking the chain.then
(a.k.ayield_self
) lets you transform elegantly.
Example:
User.new.tap { |u| u.name = "Alice" }.save
value = [1, 2, 3].then { |arr| arr.sum }
# => 6
Use tap
to peek & modify, then
to transform. π
6οΈβ£ pluck
β Faster than map
Instead of:
User.all.map(&:name)
Use:
User.pluck(:name)
It fetches only the columns you need, directly from SQL β no ActiveRecord objects loaded = β‘οΈ Faster and memory-friendly!
7οΈβ£ find_each
β Lazy Batch Processing
Donβt do:
User.all.each { |u| process(u) } # Loads all at once π«
Do this:
User.find_each(batch_size: 1000) do |user|
process(user)
end
It loads 1000 records at a time, perfect for large tables. ποΈ
8οΈβ£ attribute_before_type_cast
β Raw Value Before Casting
Want to see what was originally given before Rails casts it?
user = User.new(age: "25")
user.age # => 25 (integer)
user.age_before_type_cast # => "25" (string)
Great for debugging! π§
9οΈβ£ to_query
β Instantly Build Query Strings
Need a quick URL query?
{ name: "Alice", age: 25 }.to_query
# => "name=Alice&age=25"
Perfect for dynamic redirects & API calls. π§©
π touch
β Update updated_at
Fast
Want to bump updated_at
without changing other fields?
post.touch
It also updates belongs_to :touch
relationships!
π BONUS SECRET RECIPES!
π acts_as_list
Use the gem or your own version to easily order rows.
π enum
Define status as enum:
class Order < ApplicationRecord
enum status: [:pending, :paid, :shipped]
end
order.paid! # changes status
order.paid? # checks status
π find_or_create_by
One-liner to find or create:
User.find_or_create_by(email: "alice@example.com")
π update_columns
Update attributes without validations or callbacks (use carefully!):
user.update_columns(name: "Bob")
π silence_warnings
Run code ignoring warnings:
ActiveSupport::Deprecation.silence do
# risky code here
end
π Wrap Up
Rails is full of these magical shortcuts and hidden helpers! π Mastering them will save you time, reduce boilerplate, and make you feel like a wizard π§ββοΈ every time you code.
β¨ Which one surprised you the most? π¬ Comment below & share your own Rails secrets!
Happy coding, Rails rockstars! ππ₯π
π Like this? Save it, share it, and follow for more Ruby on Rails magic! πΎβ¨
© Lakhveer Singh Rajput - Blogs. All Rights Reserved.