Search code examples
ruby-on-railsheroku

uninitialized constant ActiveRecord::DeleteRestrictionError only when deployed to Heroku


I'm getting an uninitialized constant error when my Rails app loads on Heroku, but it works just fine in development.

Heroku Logs (breaks on boot):

/app/app/controllers/application_controller.rb:19:in `<class:ApplicationController>': uninitialized constant ActiveRecord::DeleteRestrictionError (NameError)

Relevant lines in controllers/application_controller.rb:

class ApplicationController < ActionController::API
  # ...
  # Line 19
  rescue_from ActiveRecord::DeleteRestrictionError, with: :not_processable
  # ...
end

If I comment out the rescue_from, then I get Internal Server Errors from the uncaught exception if a record fails to save due to restrict_with_error dependencies. If I do rescue from it, then the server fails to boot, but only on production.

I'm guessing this is related to eager load and/or the changes with how zeitwerk loads constants, but I haven't been able to find anything with an answer on how to fix this.


Solution

  • I found a similar sounding issue / solution from 2008:

    https://discuss.rubyonrails.org/t/rescue-from-issue-with-aws-uninitialized-constant/28759/2

    Their solution was to wrap the constant in a string to avoid file parse time issues with loading, which appears to work for this scenario as well:

    class ApplicationController < ActionController::API
      # ...
      rescue_from "ActiveRecord::DeleteRestrictionError", with: :not_processable
      # ...
    end
    

    This issue was reproduced with a minimal app, and an issue opened on Github: https://github.com/rails/rails/issues/43666