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. πŸ’»βš‘

0__Jp2pqQ1c_7qtXX_


🧠 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.