[英]Rails concerns, how to include a concern inside an api controller
I am building a Rails api and currently have this folder structure: 我正在构建Rails api,当前具有以下文件夹结构:
The error_serializer.rb file is a module: error_serializer.rb文件是一个模块:
module ErrorSerializer
extend ActiveSupport::Concern
...methods here...
end
Which I can include in any of the api controllers, for example: 我可以将其包含在任何api控制器中,例如:
class Api::TemplatesController < ApiController
include ErrorSerializer
...
end
But since this errors_serializer module is only relevant to api controllers, I want to move the file to ' api/concerns/error_serializer.rb
'. 但是,由于这个errors_serializer模块仅与api控制器相关,因此我想将文件移至“ api/concerns/error_serializer.rb
”。
But that generates the error: 但这会产生错误:
ActionController::RoutingError (uninitialized constant Api::TemplatesController::ErrorSerializer)
I tried changing the name inside the file to: 我尝试将文件内的名称更改为:
module Api::ErrorSerialzer
but got the same error. 但是出现了同样的错误。
So what must I change to be able to move that file? 那么我必须更改什么才能移动该文件?
Since rails expects your module naming to follow your file structure, your concern should be named: 由于Rails希望模块命名遵循文件结构,因此应将您的关注点命名为:
module Api::Concerns::ErrorSerializer
Since you're including it in Api::TemplatesController
, I would do: 由于您将其包含在Api::TemplatesController
,因此我将这样做:
class Api::TemplatesController < ApiController
include Api::Concerns::ErrorSerializer
...
end
To help rails out with the constant lookup. 为了帮助不断查找。
Thanks to the answer from @jvillian and this blog post , I was able to figure out the 'Rails' way to do this (since actually I will need the concern in all Api controllers, and also my api controller was outside the api namespace). 感谢@jvillian和这篇博客文章的回答,我能够弄清楚做到这一点的“ Rails”方法(因为实际上我将需要所有Api控制器的关注,而且我的api控制器不在api名称空间之外) 。 So I'm posting this solution as (I think) it's the preferred way: 因此,我发布此解决方案是因为(我认为)这是首选方式:
I moved the error_serialzier.rb file into api/concerns and change the code to include the Api namespace: 我将error_serialzier.rb文件移到api / concerns中,并更改了代码以包含Api名称空间:
module Api::Concerns::ErrorSerializer
extend ActiveSupport::Concern
...
end
I also moved api_controller.rb
file and put it inside the /api folder, and thus into the API module namespace, so now it looks like this: 我还移动了api_controller.rb
文件,并将其放在/ api文件夹中,从而放入API模块名称空间,所以现在看起来像这样:
class Api::ApiController < ActionController::API
before_action :authenticate_api_user!
include DeviseTokenAuth::Concerns::SetUserByToken
include Concerns::ErrorSerializer
respond_to :json
end
This got rid of the uninitialized constant errors. 这消除了未初始化的常量错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.