Home > Mobile >  Zeitwerk not autoloading models in rails 7
Zeitwerk not autoloading models in rails 7

Time:09-19

I recently upgraded my Rails version of my application from 6.1 to 7 and I am facing one issue with zeitwerk. I was also using the zeitwerk in my rails 6.1 which was working fine but suddenly something is breaking when I upgraded it to rails 7.

Since zeitwerk automatically loads root directories so it must autoload the models as well. But now when I try to initialise a model when booting up the server I am getting uninitialized constant error.

>> "user".camelize.constantize
=> `constantize': uninitialized constant User

I also checked this ActiveSupport::Dependencies.autoload_paths and it included the path "app/models" but still it gives the uninitialized constant error and I am not sure why.

However I tried adding the following line to my applicatio.rb file

config.autoload_once_paths << "app/models"

and then it gave me an error saying that zeitwerk was loading the same directory twice and then I had to add this line in the config/initializers/zeitwerk.rb file in order to make it work.

Rails.autoloaders.main.ignore("app/models")

At first it seemed to have fixed the problem but later it resulted in multiple test failures. So my question is that is there something I need to add in my application.rb file in order to make it work in rails 7?

Below is a snapshot of my application.rb file if that helps.

class Application < Rails::Application
    config.load_defaults 7.0
    config.autoload_once_paths << "app/models"
    config.active_record.pluralize_table_names = false
    config.assets.enabled = false
    config.api_only = true
    config.version = Dir.pwd.split('/').last
    config.action_dispatch.ip_spoofing_check = false
  end

CodePudding user response:

This is unrelated to the configuration. Please do not change config.autoload_once_paths or any autoloading configuration.

As explained in the upgrading guide, in Rails 7 you cannot autoload constants when the application boots. Your application on Rails 6 was already issuing warnings about this with instructions about how to address them.

Please follow the instructions in the upgrading guide to fix it.

  • Related