首页 > 解决方案 > 仅生产环境?- 未初始化的常量 ActiveRecord::AssociationNotFoundError (NameError) - 异常

问题描述

uninitialized constant ActiveRecord::AssociationNotFoundError (NameError)只在我的生产环境中使用,开发/登台工作正常。当我注释掉生产中运行的代码中的行时,顺便说一句,在 docker 容器中,代码运行良好。

我里面有这个异常处理模块controller/concerns

该模块包含在Application Controller

该行:

rescue_from ActiveRecord::AssociationNotFoundError do |e|
  json_response({  status: '422', details: [ { message: e.message }  ] }, :unprocessable_entity)
end

config/environments/production

Rails.application.configure do

    config.cache_classes = true
  
    config.hosts << "www.example.com"
    config.hosts << "limpar-api"
    config.cache_store = :redis_cache_store, { url: ENV.fetch("REDIS_URL_CACHING", "redis://localhost:6379/0") }
  
    config.eager_load = true
 
    config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
  
    config.active_storage.service = :local
  
    config.log_level = :debug
  
    config.log_tags = [ :request_id ]
  
    config.action_mailer.perform_caching = false
    config.i18n.fallbacks = true
  
    config.active_support.deprecation = :notify
  
    config.log_formatter = ::Logger::Formatter.new
  
    if ENV["RAILS_LOG_TO_STDOUT"].present?
      logger           = ActiveSupport::Logger.new(STDOUT)
      logger.formatter = config.log_formatter
      config.logger    = ActiveSupport::TaggedLogging.new(logger)
    end
  
    config.active_record.dump_schema_after_migration = false
  
  end

config/environments/staging

Rails.application.configure do
  
    config.active_record.migration_error = false
  
    config.active_record.verbose_query_logs = true
end
  

知道为什么吗?

标签: ruby-on-railsrubyactiverecord

解决方案


@queroga_vqz 你能用包含模块的完整代码更新问题吗?我想我现在明白了这个错误:

  • 在生产中,rails 使用“eager_loading”在应用启动时加载app/ 下的所有 .rb 。-> 也许尝试将其更改为在开发config/environments/development.rbconfig.eager_loading = true具有相同的行为以进行调试
  • 解决的一个想法:加载关注点时不加载 ActiveRecord(也许急切加载在模型之前加载控制器?)。修复想法:除了您的关注之外,请尝试:
require "active_record/all"
# or
require "active_record/associations"
  • 其他想法,更改为 AS::Concern 并包含(如果还没有):
module ExceptionHandlingConcern
  extend ActiveSupport::Concern
  included do 
    rescue_from ...
  end
end

推荐阅读