zeitwerk: Uninitialized constant with nested models Rails 6 upgrade
The issue
I’m almost certain I’m doing something simple wrong here, but I’ve been stuck on this for a few days now without success after much searching and experimentation.
I’m upgrading a Rails project from Rails 5 to Rails 6.0.4.1
(Ruby 2.7.3
), and trying to get various models and classes loading using zeitwerk 2.4.2
.
Some of my nested classes within an app/models/api
folder seemingly aren’t discovered or aren’t loaded by zeitwerk. For example:
models/user.rb -> User (loads)
models/api/base.rb -> Api::Base (does not load)
models/api/person.rb -> Api::Person (does not load)
models/api/person/address.rb -> Api::Person::Address (does not load)
Some observations
1 - My Api::Base
class loads when defined within a explicit module like so:
module Api
class Base
end
end
But the more succinct class Api::Base
does not…
2 - I’ve also noticed that if I delete the /models/api/person
directory, I can get the Api::Person class to load using the same explicit module approach above.
3 - Lastly, when I call Api.constants
, I can see both Base
and Person
in the result:
> Api.constants
=> [
:Base,
:Person]
…but calling const_get on either of them gives me the uninitialized constant error.
To test all this, I’ve been firing up a rails console and just trying to use the models like so:
rails c
Loading development environment (Rails 6.0.4.1)
> Api::Person
NameError: uninitialized constant Api::Person
from (pry):1:in `__pry__'
I feel like I should apologize in advance for what’s likely to be a complete misunderstanding on my end. I keep coming back to the explicit namespaces section of the documentation and wondering why this isn’t working.
Any assistance anyone could offer would be much appreciated.
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Comments: 21 (12 by maintainers)
Something is off, that kind of directory structure works routinely well since the beginning.
I added a few traces in recent commits, could you please upgrade to
2.5.0.beta3
and run the previous command again?