Skip to content

/errors/ruby/uninitialized-constant

Ruby: uninitialized constant Name (NameError)

The commands on this page have not been executed by our verification runner yet.updated
tool
Ruby
exit code
1
versions
Ruby 2.x, Ruby 3.x, Rails 6+ (Zeitwerk)
os
any

uninitialized constant Name (NameError) means Ruby reached a reference to Name, a class, module or constant, and no definition was loaded under that name in the current namespace. In a plain Ruby script the fix is usually a missing require / require_relative or a typo. In Rails it usually means the file name does not match the class name, so the autoloader (Zeitwerk) never loads it; the message then shows the namespace where Ruby looked, for example uninitialized constant Admin::UsersController::User.

Example

main.rb
puts Invoice.new.total     # invoice.rb was never required
text
main.rb:1:in '<main>': uninitialized constant Invoice (NameError)

Fixes

ruby
require_relative 'invoice'          # load the file that defines Invoice
require 'json'                      # constants from the standard library or gems need require too
puts JSON.generate({ ok: true })

module Admin
  class Report
    def user = ::User.first         # :: forces the top-level User, not Admin::User
  end
end

Rails file names

FileMust define
app/models/user.rbUser
app/models/user_account.rbUserAccount
app/models/admin/user.rbAdmin::User
app/services/pdf_export.rbPdfExport (or configure the PDF acronym in an inflector)
bash
bin/rails zeitwerk:check     # lists files whose names do not match their constants

Sources