如何在 Rails 中正确设置、制造或包含关注
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
#然后include like,include Admin::Test
如何在我的管理控制器中正确调用或包含测试问题。
class Admin::ShopsController < Admin::BaseController
include Admin::Test # doing this,
# got uninitialized constant Admin::Test
end
官方指南中有相关说明
All right, Rails has a collection of directories similar to $LOAD_PATH in which to look up post.rb. That collection is called autoload_paths and by default it contains:
Any existing second level directories called app/*/concerns in the application and engines.
https://guides.rubyonrails.org/autoloading_and_reloading_constants.html
未加载app/controllers/admin/concerns
的原因是它不是二级目录。
由于二级目录中的文件是自动加载的,在这种情况下,您应该将 test.rb 文件放在 app/controllers/concerns/admin
.
或将 app/controllers/admin/concerns
添加到自动加载路径,但不强烈推荐,因为这不符合 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
#然后include like,include Admin::Test
如何在我的管理控制器中正确调用或包含测试问题。
class Admin::ShopsController < Admin::BaseController
include Admin::Test # doing this,
# got uninitialized constant Admin::Test
end
官方指南中有相关说明
All right, Rails has a collection of directories similar to $LOAD_PATH in which to look up post.rb. That collection is called autoload_paths and by default it contains:
Any existing second level directories called app/*/concerns in the application and engines.
https://guides.rubyonrails.org/autoloading_and_reloading_constants.html
未加载app/controllers/admin/concerns
的原因是它不是二级目录。
由于二级目录中的文件是自动加载的,在这种情况下,您应该将 test.rb 文件放在 app/controllers/concerns/admin
.
或将 app/controllers/admin/concerns
添加到自动加载路径,但不强烈推荐,因为这不符合 rails 设计模式。