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.
undefined method for nilundefined method `[]' for nilfor nil:NilClass 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
- Use find (raises 404) or handle nil explicitly
- Use safe navigation (&.) where nil is valid
- Check params with require/permit and defaults
Detailed fix by platform
Ruby
- ruby
user = User.find_by(email: params[:email]) return head :not_found unless user puts user.profile&.bio
How to diagnose
- Receiver — Which object is nil (line in trace)?
- 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:
Similar errors
- ActionController::InvalidAuthenticityToken Rails: ActionController::InvalidAuthenticityToken (Can't verify CSRF token authenticity)
- ActionController::UrlGenerationError: No route matches {action...} missing required keys Rails: ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"users", :id=>nil}, missing required keys: [:id]
- ActionView::Template::Error: undefined method for nil in view Rails: ActionView::Template::Error (undefined method `name' for nil:NilClass): app/views/users/show.html.erb:3
Most viewed in Ruby / Rails
- LoadError: cannot load such file Ruby: LoadError: cannot load such file -- nokogiri (or: cannot load such file -- bundler/setup)
- Your Ruby version is X, but your Gemfile specified Y Bundler: Your Ruby version is 3.1.2, but your Gemfile specified 3.3.0
- CORS blocked in Rails API (rack-cors) Browser: Access to fetch at 'http://localhost:3000/api/items' from origin 'http://localhost:5173' has been blocked by CORS policy — Rails
Other ways to find it
Where this error sits
Origin: Application & API. Errors that are often confused with or caused by this one (click to open):
🧠 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.
💬 What worked for others
No tips yet — did something else fix this for you?
Share what worked for you
Tips are checked by an editor before they appear. Links are removed.
Report a correction or suggest an improvement
Last updated 14 Oct 2026