ruby-on-rails - 为什么在Rails中安装路由会因 “uninitialized constant API”而失败?

标签 ruby-on-rails rails-routing grape

我正在开发一个包含使用API gem的grape的应用程序。

这是我的Root类:

module API
  class Root < Grape::API
    rescue_from :all do |e|
      Rack::Response.new(
        [ "Error: #{e.message}" ],
        500,
        { "Content-type" => "text/error" }
      ).finish
    end

    prefix "api"
    version 'v1', using: :path
    format :json
    error_format :json

    mount ::API::ServiceRequests
  end
end

这是我在路线上安装它的方式:
mount API::Root => '/'
我收到的错误是:
'中的routes.rb:45:in块:未初始化的常量API(NameError)`

这些文件的结构类似于app/api/root.rb,我在application.rb中有以下代码要加载到文件中:
config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb')
config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]

最佳答案

尝试将API代码的文件从app/api移到app/api/api

Grape's documentation:

Place API files into app/api. Rails expects a subdirectory that matches the name of the Ruby module and a file name that matches the name of the class. In our example, the file name location and directory for Twitter::API should be app/api/twitter/api.rb.



因此,您的API::Root类的正确位置实际上是app/api/api/root.rb

关于ruby-on-rails - 为什么在Rails中安装路由会因 “uninitialized constant API”而失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24833131/

相关文章:

ruby-on-rails - rails 将 check_box_tag 条目大写

ruby-on-rails - 将集合与相关对象分组

ruby-on-rails - 如何动态添加路由到 Rails3 中的作用域资源?

ruby-on-rails - 为什么 ActionDispatch::Routing::RouteSet 需要这么长时间

ruby-on-rails - rails : Returning errors from Module to Rake task?

ruby-on-rails - 如何在时间范围内获取记录

ruby-on-rails - Ruby on Rails:根据路径获取 Controller 和 Action 名称

ruby-on-rails - Rails 如何以及何时加载 gem 库?

grails - 让 Groovy 成功!