简体   繁体   中英

Rails concerns, how to include a concern inside an api controller

I am building a Rails api and currently have this folder structure:

在此处输入图片说明

The error_serializer.rb file is a module:

module ErrorSerializer
  extend ActiveSupport::Concern

  ...methods here...
end

Which I can include in any of the api controllers, for example:

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 '.

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:

module Api::Concerns::ErrorSerializer

Since you're including it in Api::TemplatesController , I would do:

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). 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:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM