【问题标题】:Circular dependency detected while autoloading constant Concerns::<NameOfConcern>自动加载常量 Concerns::<NameOfConcern> 时检测到循环依赖
【发布时间】:2016-05-17 14:36:28
【问题描述】:

注意:在您考虑将此问题标记为其他类似问题的重复之前,请注意这一点,即该问题是针对 Rails 中的问题提出的,而我搜索的其他问题涉及控制器。我没有发现任何问题,这与关注有关。

我在app/models/concerns 中有一个名为 cmets_deletion.rb 的文件,它包含以下代码:

module CommentsDeletion
  extend ActiveSupport::Concern

  included do
    after_save :delete_comments, if: :soft_deleted?
  end

  def soft_deleted?
    status == 'deleted'
  end

  def delete_comments
    comments.each &:destroy
  end
end

我正在尝试通过编写以下代码在我的模型中混合文件:

class Employee < ActiveRecord::Base
  include CommentsDeletion
  # all the other code
end

只是这样做,然后在调用 rails console 时,它给了我以下错误:

Circular dependency detected while autoloading constant Concerns::CommentsDeletion

我使用的是 Rails 4.0.2,这件事让我发疯了,我无法弄清楚我的代码有什么问题。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 models activesupport-concern


    【解决方案1】:

    很奇怪,Rails 文档中的任何地方都没有提到以下内容,但是有了它,我的代码就可以正常工作了。

    您所要做的就是将CommentsDeletion 替换为Concerns::CommentsDeletion。否则,您必须将 Concerns 放在您希望稍后混入模型的模块名称之前。

    现在,这就是我的模块驻留在关注目录中的样子:

    module Concerns::CommentsDeletion
      extend ActiveSupport::Concern
    
      included do
        after_save :delete_comments, if: :soft_deleted?
      end
    
      def soft_deleted?
        status == 'deleted'
      end
    
      def delete_comments
        comments.each &:destroy
      end
    end
    

    【讨论】:

    • 非常感谢您回答您自己的问题。奇怪的是,这在开发中运行良好,并且在我推到登台时引起了问题。感谢分期!
    • @abhishek77in 啊,过去。现在,在 Rails 5 中,即使没有在开头添加 Concerns::,它也能完美运行。
    【解决方案2】:

    就我而言,我的代码喜欢这样:

    #models/user.rb
    class User < ApplicationRecord
      include User::AuditLog
    end
    

    #model/concern/user/audit_log.rb
    module User::AuditLog
      extend ActiveSupport::Concern
    end
    

    它在开发环境中运行良好,但在生产中却出现标题错误。当我更改为这个时,它对我来说很好。如果与模型同名,则重命名相关文件夹名称。

    #models/user.rb
    class User < ApplicationRecord
      include Users::AuditLog
    end
    

    #model/concern/users/audit_log.rb
    module Users::AuditLog
      extend ActiveSupport::Concern
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多