Home > Mobile >  Rails 7 app - getting 'uninitialized constant' error while referencing Model files
Rails 7 app - getting 'uninitialized constant' error while referencing Model files

Time:09-19

running a rails 7.0.x app and running into an uninitialized constant error anytime it references a Model class that's in app/models

so I have a service class in

app/services/sales_service.rb

Service Class:

class SalesService
  def gensalesdata
   print "TESTING: #{AuthorSale.last} \n"
  end
end

and it's invoked by a rake task:

task :testtask1 do
   SalesService.new.gensalesdata
end

It is making a call to a basic model file called AuthorSale , which is located in

app/models/author_sale.rb

the model file code is:

class AuthorSale < ApplicationRecord
end

and even if i do a simple AuthorSale.last call from the service class, i get that error:

uninitialized constant SalesService::AuthorSale
  • ran a bin/rails zeitwerk:check check and it returned with a Hold on, I am eager loading the application. All is good! response
  • config.eager_load = true is set in the config/environments/development.rb file
  • went through dozens of other similar posts on SO and none of them seemed to solve my issue.
  • The underlying table name in MySQL is author_sales
  • The stranger issue is that this same code works just fine if i invoke it from the Rails console. It stops working if the code is run from the command line via a Rake task or from a web server

UPDATE:

  • Two more issues discovered while debugging this that when i add this to config/environments/development.rb:
  config.eager_load = true
  print "#{ActiveSupport::Dependencies.autoload_paths}"

the flow is not even entering that file even though the RAILS_ENV is set to development

and when i print out the same ActiveSupport::Dependencies.autoload_paths right inside the service class file, it prints out an empty array, which is further proof that the app is unable to find/load any of the app/models files

what am i missing?

CodePudding user response:

You may have to link your rake task to an environment :

task testtask1: :environment do
   SalesService.new.gensalesdata
end
  • Related