0

我正在寻找有关在 Grape 中声明 API 资源路径的语法的说明。下面的示例声明了资源路径“/items”、“/items/:id”、“/objects”和“/objects/:id”。我不明白的是为什么“/items/:id”的定义返回null?

class API < Grape::API

  format :json
  default_format :json

  rescue_from :all, backtrace: true


  resource :items do

    desc "Returns an array of all items."
    get do
      ITEMS.find.to_a
    end

    desc "Returns an item by its id."
    get '/:id' do

      # hardcoding the document id returns the correct document
      # ITEMS.find_one( "item_id" => 2519 )

      # using the path parameter :id returns null, why???
      ITEMS.find_one( "item_id" => params[:id] )
    end
  end


  resource :objects do

    desc "Returns an array of all objects."
    get do
      OBJECTS.find.to_a
    end

    ##
    # using the route_param syntax correctly returns the document
    # resource path /objects/:id
    ##
    desc "Returns an object by its id."
    params do
      requires :id, type: Integer
    end
    route_param :id do
      get do
        OBJECTS.find_one( "object_id" => params[:id] )
      end
    end
  end

end
4

1 回答 1

2

Your use of resource and route methods is ok.

You have a problem with parameter processing - params[:id] is a String by default. Your example hard-coded value that works is aFixnum (integer).

Probably your (not shown) code that queries the list on ITEMS is looking up integer values.

You could use ITEMS.find_one( "item_id" => params[:id].to_i ) to convert the param inline.

However, you probably should use a params description block to get Grape to convert for you, as you already are for OBJECTS:

desc "Returns an item by its id."
params do
  requires :id, type: Integer
end
get '/:id' do
  ITEMS.find_one( "item_id" => params[:id] )
end
于 2014-02-10T23:27:23.013 回答