如何在Rails中正确设置,关注或包含关注点

时间:2018-09-24 06:34:23

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

通常,问题位于

app/controllers/concerns

但是我想在管理员方面提出并分开考虑。

app/controllers/admin/concerns

鉴于我设置了一些示例代码,

# app/controllers/admin/concerns/test.rb
module Test
  extend ActiveSupport::Concern

  included do
    before_action :test
  end

  def test
    render json: 'test concern'
  end
end

#还尝试了...,

module Admin
  module Test
    extend ActiveSupport::Concern

    included do
      before_action :test
    end

    def test
      render json: 'test concern'
    end
  end
end

#然后包括like,包括Admin :: Test

如何在我的管理员中正确调用或包含测试问题。

class Admin::ShopsController < Admin::BaseController
   include Admin::Test # doing this,
   # got uninitialized constant Admin::Test
end

1 个答案:

答案 0 :(得分:0)

相关说明已写在官方指南中。

  

好的,Rails有一个类似于$ LOAD_PATH的目录集合,可在其中查找post.rb。该集合称为autoload_paths,默认情况下包含:

     

应用程序和引擎中任何现有的名为app / * / concerns的二级目录。

https://guides.rubyonrails.org/autoloading_and_reloading_constants.html

未加载app/controllers/admin/concerns的原因是它不是第二级目录。

由于第二级关注目录中的文件会自动加载,因此在本例中,您将test.rb文件放入了app/controllers/concerns/admin中。

或在自动加载路径中添加app/controllers/admin/concerns,但不建议这样做,因为这超出了Rails的设计模式。