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! πŸ§™β€β™‚οΈβœ¨

1_iP7tRgSsM7k-osyDTKQyYw

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.a yield_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.