4

I'm trying to create an api controller for a model defined in a module

Model class:

module Reports
  class Report < ActiveRecord::Base
  end
end

Api controller:

class API::V2::ReportsController < API::V2::BaseController

end

Route:

namespace :api, defaults: { format: :json } do
  namespace :v2 do
    resources :reports
  end
end

The error I get when try to call api/v2/reports is:

LoadError (Unable to autoload constant Report, expected /.../app/models/reports/report.rb to define it):

Is there a way to solve this, making the api controller look for Reports::Report instead of Report?

baldarn
  • 2,842
  • 2
  • 13
  • 13
  • There is no way to achieve this. You need write Reports::Report all the time. But I wonder why you need namespaced model? – andriy-baran Jun 26 '18 at 14:29
  • @andriy-baran I have to isolate the model for colliding names. So you are saying all models should be defined as root?? – baldarn Jun 26 '18 at 14:34
  • Please read this question https://stackoverflow.com/questions/18934115/rails-4-organize-rails-models-in-sub-path-without-namespacing-models – andriy-baran Jun 26 '18 at 14:39

1 Answers1

0

Your controller needs to include Reports somehow:

module Api
  module V2
    module Reports
      class Report < API::V2::BaseController

        your controller actions

      end
    end
  end
end

Apart from that, I think it will be confusing if you use Reports::Report?

Emilio Menéndez
  • 1,932
  • 2
  • 11
  • 20
  • I tried also this, but with no luck. It gives me the same error – baldarn Jun 26 '18 at 14:47
  • what's the path file for your Reports:Report? should be `./app/models/reports/report.rb` as the error you get suggests – Emilio Menéndez Jun 26 '18 at 14:49
  • the path is that – baldarn Jun 26 '18 at 14:52
  • I just realised your routes are missing one nested namespace for `reports` as well, but the whole naming looks weird to me and not sure if rails will be getting confused. The module's name should be singular and then you might have a Finance report or something, `Reports::Report` is confusing in my opinion – Emilio Menéndez Jun 26 '18 at 15:32
  • I also tried with a different naming, changing Reports::Report with Reporting::Report and consequently all the classes and controller. I also tried to add the Reporting namespace but the error is always the same – baldarn Jun 26 '18 at 15:35