Ошибка маршрутизации винограда - маршрут не соответствует действию для пространства имен + объяснение

У меня есть простое приложение Rails с конечной точкой Grape API. Я следовал этому руководству, поэтому я установил все как есть. , просто заменили гусар для юзеров. У меня проблемы с тем, чтобы это работало, потому что мои маршруты, кажется, повреждены. У меня есть следующая структура папок:

├── app
│   ├── controllers
│   │   ├── api
│   │   │   ├── base.rb
│   │   │   └── v2
│   │   │       ├── api.rb
│   │   │       ├── defaults.rb
│   │   │       └── users.rb

base.rb

module API
  class Base < Grape::API
    mount API::V2::Api
  end
end

api.rb

module API
  module V2
    class Api < Grape::API
      mount API::V2::Users
    end
  end
end

users.rb

module API
  module V2
    class Users < Grape::API
      include API::V2::Defaults

      group :tests do
          get "/test_1" do
          { test: "all"}
        end
      end


        get "/hello" do
            User.all.to_json
        end

        get '/rt_count' do
          { rt_count: "current_user.rt_count" }
        end
    end
  end
end

и в моем Defaults.rb у меня есть следующий код:

module API
  module V2
    module Defaults
      extend ActiveSupport::Concern

      included do

        version 'v2', using: :path
        default_format :json
        format :json
        content_type :json, 'application/json'

        #formatter :json, Grape::Formatter::ActiveModelSerializers

        rescue_from Mongoid::Errors::DocumentNotFound do |e|
          error_response(message: e.message, status: 404)
        end
      end
    end
  end
end

routes.rb

Rails.application.routes.draw do

  mount API::Base => '/api'

Список маршрутов (используя gem 'grape-rails-routes'):

                GET     /:version/tests/test_1(.:format)           API::V2::Users
                GET     /:version/hello(.:format)                  API::V2::Users
                GET     /:version/rt_count(.:format)               API::V2::Users
                OPTIONS /:version/tests/test_1(.:format)(.:format) API::V2::Users
                PUT     /:version/tests/test_1(.:format)(.:format) API::V2::Users
                POST    /:version/tests/test_1(.:format)(.:format) API::V2::Users
                DELETE  /:version/tests/test_1(.:format)(.:format) API::V2::Users
                PATCH   /:version/tests/test_1(.:format)(.:format) API::V2::Users
                OPTIONS /:version/hello(.:format)(.:format)        API::V2::Users
                PUT     /:version/hello(.:format)(.:format)        API::V2::Users
                POST    /:version/hello(.:format)(.:format)        API::V2::Users
                DELETE  /:version/hello(.:format)(.:format)        API::V2::Users
                PATCH   /:version/hello(.:format)(.:format)        API::V2::Users
                OPTIONS /:version/rt_count(.:format)(.:format)     API::V2::Users
                PUT     /:version/rt_count(.:format)(.:format)     API::V2::Users
                POST    /:version/rt_count(.:format)(.:format)     API::V2::Users
                DELETE  /:version/rt_count(.:format)(.:format)     API::V2::Users
                PATCH   /:version/rt_count(.:format)(.:format)     API::V2::Users
                GET     /:version/tests/test_1(.:format)           API::V2::Api
                GET     /:version/hello(.:format)                  API::V2::Api
                GET     /:version/rt_count(.:format)               API::V2::Api
                OPTIONS /:version/tests/test_1(.:format)(.:format) API::V2::Api
                PUT     /:version/tests/test_1(.:format)(.:format) API::V2::Api
                POST    /:version/tests/test_1(.:format)(.:format) API::V2::Api
                DELETE  /:version/tests/test_1(.:format)(.:format) API::V2::Api
                PATCH   /:version/tests/test_1(.:format)(.:format) API::V2::Api
                OPTIONS /:version/hello(.:format)(.:format)        API::V2::Api
                PUT     /:version/hello(.:format)(.:format)        API::V2::Api
                POST    /:version/hello(.:format)(.:format)        API::V2::Api
                DELETE  /:version/hello(.:format)(.:format)        API::V2::Api
                PATCH   /:version/hello(.:format)(.:format)        API::V2::Api
                OPTIONS /:version/rt_count(.:format)(.:format)     API::V2::Api
                PUT     /:version/rt_count(.:format)(.:format)     API::V2::Api
                POST    /:version/rt_count(.:format)(.:format)     API::V2::Api
                DELETE  /:version/rt_count(.:format)(.:format)     API::V2::Api
                PATCH   /:version/rt_count(.:format)(.:format)     API::V2::Api
                GET     /:version/tests/test_1(.:format)           API::Base
                GET     /:version/hello(.:format)                  API::Base
                GET     /:version/rt_count(.:format)               API::Base

Во-первых, меня немного смущают маршруты, которые изначально генерируются из Grape. У меня есть несколько вопросов:

  1. Почему Grape дважды указывает формат для некоторых API? (.:format)(.:format)
  2. Почему у меня две записи для большинства API? Мне кажется, что это вызвано кодом в файле api.rb
  3. Дополнительный вопрос: как отключить обработку XML в Rails. Я хочу поддерживать только JSON

А теперь самое смешное: когда я вызываю запрос:

  1. http://lclhost.com:3000/api/v2/hello.json - API работает как положено
  2. http://lclhost.com:3000/api/v2/rt_count.json - API работает как положено
  3. http://lclhost.com:3000/api/v2/tests/test_1.json – API не работает, возвращается Нет совпадений маршрута [GET] "/api/v2/tests/test_1.json"

Я почти уверен, что в пространстве имен Grape есть небольшая настройка или конфигурация, которую я не могу найти.


person Tom Hert    schedule 09.12.2014    source источник


Ответы (2)


Я думаю, это потому, что group — это блок определения параметра, а не блок маршрута, измените его на namespace.

person dB.    schedule 09.12.2014
comment
См. мой комментарий на: github.com/intridea/grape/issues/846# issuecomment-66325279 - person Tom Hert; 09.12.2014

Замените users.rb этим кодом

module API
  module V2
    class Users < Grape::API
      include API::V2::Defaults

      resource :tests do

        get "/test_1" do
          { test: "all"}
        end


        get "/hello" do
            { User.all.to_json }
        end

        get '/rt_count' do
          { rt_count: "current_user.rt_count" }
        end

       end

    end

  end

end
person Manoj Thapliyal    schedule 30.06.2016