Rails 葡萄 API 'id is invalid' 在不需要 id 的请求中

Rails Grape API 'id is invalid' in request that requires no id

我有一颗受 Doorkeeper 保护的葡萄 API,我有很多方法可以完美运行。但是,有一种方法表现得很奇怪。 这是一个不需要参数的 GET 请求,运行 它会抛出以下错误:

Grape::Exceptions::ValidationErrors at /v1/discount_cards/all.json

id is invalid

我的方法是这样的:

desc 'Get all the cards of current customer'
params {}
get 'all' do
  current_customer.discount_cards.to_json(include:
  {
    barcode: {
      include: :barcode_type
    }
  })
end

日志显示错误发生在 logger.rb 文件的第 17 行,如下所示:

module API
  class Logger
    def initialize(app)
      @app = app
    end

    def call(env)
      payload = {
        remote_addr: env['REMOTE_ADDR'],
        request_method: env['REQUEST_METHOD'],
        request_path: env['PATH_INFO'],
        request_query: env['QUERY_STRING'],
        x_organization: env['HTTP_X_ORGANIZATION']
      }

      ActiveSupport::Notifications.instrument 'grape.request', payload do
        @app.call(env).tap do |response| # <-- logs say the error is here
          payload[:params] = env['api.endpoint'].params.to_hash
          payload[:params].delete('route_info')
          payload[:params].delete('format')
          payload[:response_status] = response[0]
        end
      end
    end
  end
end

我的主要 base.rb class 看起来像这样:

module API
  class Dispatch < Grape::API
    mount API::V1::Base
  end

  Base = Rack::Builder.new do
    use API::Logger
    run API::Dispatch
  end
end

我真的无法理解 id 它在说什么,而且,所有其他 api 方法都工作得很好(post、get、put、delete)。

你能帮我解决这个问题吗?

我最近也有这个问题,结果是我的代码顺序问题。我找到了答案 here.

Grape evaluates routes in order, so with two routes, /:id and /nearby_missions, it matches /:id first, making id=nearby_missions. Then it tries to coerce nearby_missions into an Integer which fails, and you get the missing id error.

You could "fix" this by adding requirements: /\d*/ to the first route (didn't test), but you're probably just better off ordering them in the order you want them to be evaluated, which is what you did.

你的问题中没有足够的信息让我确定这也是你的问题,但很可能是!