2014-02-10 1 views
0

포도에서 API 리소스 경로를 선언하는 구문에 대한 설명을 찾고 있습니다. 아래 예제는 "/ items", "/ items/: id", "/ objects"및 "/ objects/: id"리소스 경로를 선언합니다. undestand가 "/ 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 

답변

2

resourceroute 방법의 사용은 괜찮습니다.

매개 변수 처리에 문제가 있습니다. params[:id]은 기본적으로 String입니다. 작동하는 예제 하드 코드 값은 Fixnum (정수)입니다.

아마도 ITEMS에서 목록을 쿼리하는 (표시되지 않은) 코드가 정수 값을 찾고있을 것입니다.

ITEMS.find_one("item_id" => params[:id].to_i)을 사용하면 param 인라인을 변환 할 수 있습니다. 이미 객체에 대한 마찬가지로

그러나, 당신은 아마 당신을 위해 변환 포도를 얻기 위해 params 설명 블록을 사용한다 :

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