【问题标题】:Unable to autoload constant API Controller in Rails 4 model in module无法在模块中的 Rails 4 模型中自动加载常量 API 控制器
【发布时间】:2018-12-05 07:29:44
【问题描述】:

我正在尝试为模块中定义的模型创建一个 api 控制器

模型类:

module Reports
  class Report < ActiveRecord::Base
  end
end

API 控制器:

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

end

路线:

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

我尝试调用 api/v2/reports 时遇到的错误是:

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

有没有办法解决这个问题,让 api 控制器寻找 Reports::Report 而不是 Report?

【问题讨论】:

  • 没有办法做到这一点。你需要一直写 Reports::Report。但我想知道为什么你需要命名空间模型?
  • @andriy-baran 我必须隔离模型以冲突名称。所以你是说所有模型都应该定义为root??

标签: ruby-on-rails ruby api ruby-on-rails-4


【解决方案1】:

您的控制器需要以某种方式包含Reports

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

        your controller actions

      end
    end
  end
end

除此之外,我认为如果你使用Reports::Report会很混乱?

【讨论】:

  • 我也试过这个,但没有运气。它给了我同样的错误
  • Reports:Report 的路径文件是什么?应该是./app/models/reports/report.rb,因为你得到的错误提示
  • 路径是那个
  • 我刚刚意识到您的路由也缺少一个嵌套的 reports 命名空间,但是整个命名对我来说看起来很奇怪,并且不确定 Rails 是否会混淆。模块的名称应该是单数,然后你可能有财务报告或其他东西,Reports::Report 在我看来很混乱
  • 我还尝试了不同的命名,将 Reports::Report 更改为 Reporting::Report 以及所有类和控制器。我也尝试添加 Reporting 命名空间,但错误始终相同
猜你喜欢
  • 2016-09-03
  • 2014-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-19
相关资源
最近更新 更多