【问题标题】:Production env only? - uninitialized constant ActiveRecord::AssociationNotFoundError (NameError) - Exception仅生产环境? - 未初始化的常量 ActiveRecord::AssociationNotFoundError (NameError) - 异常
【发布时间】:2021-04-21 15:48:13
【问题描述】:

我只在我的生产环境中收到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
  

知道为什么吗?

【问题讨论】:

  • 什么版本的 Rails?
  • 你注释掉了哪些行?什么是关联(belongs_to/has_many)?您是否也在生产环境中运行了所有迁移? (dev + prod中的数字是否相同:echo "select count(*) from schema_migrations;" | rails dbconsole -p
  • @Unixmonkey 我正在使用 rails 6,ruby 2.7.1
  • 嗨@stwienert,感谢您抽出宝贵时间,我将上面提到的rescue_from 子句注释掉,目的是当它捕获到该异常时返回一个错误,alltought,服务器永远不会开始。是的,我运行了所有迁移。

标签: ruby-on-rails ruby activerecord


【解决方案1】:

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

  • 在生产中,rails 使用“eager_loading”在应用启动时加载 app/ 下的所有 .rb。 -> 也许可以尝试将 config/environments/development.rb 更改为 config.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

【讨论】:

  • 非常感谢@stwienert,require "active_record/associations" 成功了。感谢您的额外解释。我的模块的完整代码正是您在第二条报价消息中键入的内容(它只是有更多的救援子句)。我尝试使用 `require "active_record/all" 但出现(加载错误)无法加载此类文件。
猜你喜欢
  • 2013-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-26
  • 2016-09-15
  • 2015-02-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多