Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

enter image description here

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?

like image 617
rmcsharry Avatar asked Sep 14 '25 11:09

rmcsharry


1 Answers

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.

like image 120
jvillian Avatar answered Sep 17 '25 04:09

jvillian