自动加载常量问题:: <nameofconcern>时检测到循环依赖性

时间:2016-05-17 14:36:29

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

注意:在您考虑将此问题标记为其他类似问题的副本之前,请注意这个问题是在Rails中询问此问题,而我搜索过的其他问题与控制器有关。毫无疑问,我发现了这一问题。

我在app/models/concerns内有一个名为 comments_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,这件事让我疯狂,而且我无法弄清楚我的代码有什么问题。

2 个答案:

答案 0 :(得分:1)

非常奇怪Rails文档中没有提到以下内容,但有了它,我的代码没有任何问题。

您所要做的就是将CommentsDeletion替换为Concerns::CommentsDeletion。换句话说,您必须将Concerns放在模块名称之前,以便稍后将其混合到模型中。

现在,我的模块驻留在Concer目录中的方式如下:

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

答案 1 :(得分:0)

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

#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