undefined method for nil 💎 Ruby / Rails

Ruby: NoMethodError: undefined method `x' for nil (nil:NilClass)

You called a method on nil — the object you expected (a record, hash value, param) wasn’t there.

Seen on: Ruby

Meaning

In Rails it’s usually a find_by returning nil, a missing association, params[:x] absent, or an instance variable not set in the controller for the view.

Common causes

  • find_by/first returned nil (no matching record)
  • Association not present (user.profile is nil)
  • Missing params or hash key
  • Instance variable not set for the view

⚡ Quick fix

  1. Use find (raises 404) or handle nil explicitly
  2. Use safe navigation (&.) where nil is valid
  3. Check params with require/permit and defaults

Detailed fix by platform

Ruby

  1. ruby
    user = User.find_by(email: params[:email])
    return head :not_found unless user
    puts user.profile&.bio

How to diagnose

  1. Receiver — Which object is nil (line in trace)?
  2. Data — Does the record exist?

🔧 Still not fixed?

Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.