[英]How to properly set up, make or include concern in Rails
通常,关注点位于
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
# 然后包含喜欢,包含 Admin::Test
如何在我的管理控制器中正确调用或包含测试问题。
class Admin::ShopsController < Admin::BaseController
include Admin::Test # doing this,
# got uninitialized constant Admin::Test
end
相关解释已经写在官方指南中。
好吧,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 设计模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.