ruby-on-rails - 自动加载常量 Concerns::<NameOfConcern> 时检测到循环依赖

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

注意:在您考虑将此问题标记为其他类似问题的重复之前,请注意这个问题是关于 Rails 中的问题,而我搜索过的其他问题涉及 Controller 。毫无疑问,我已经发现,这涉及到关注。

我在 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,这件事让我抓狂,我无法弄清楚我的代码有什么问题。

最佳答案

非常奇怪,Rails 文档中的任何地方都没有提到以下内容,但有了它,我的代码可以正常运行。

您只需将 CommentsDeletion 替换为 Concerns::CommentsDeletion。换句话说,您必须在以后要混入模型的模块名称前加上 Concerns

现在,这就是我驻留在 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

关于ruby-on-rails - 自动加载常量 Concerns::<NameOfConcern> 时检测到循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37279193/

相关文章:

ruby-on-rails - 如何在 vim 编辑器中使用 bundler 打开 gem 源代码

ruby-on-rails - rails |在连接查询中添加条件

Android 自定义 Listview 未显示

ruby-on-rails - 如何为我的 rails 应用程序扩展 sidekiq 性能。需要每秒运行 100 个 sidekiq 作业

ruby-on-rails - 测试中没有路由错误在开发中工作

ruby-on-rails - 如何将 id 传递给新用户路径?

ruby-on-rails - Rails 4 中的强参数和查找

python - 如何使用两个不同的配置文件扩展 Django 用户模型?

php - 找不到 laravel 5 模型类