2014-02-10 34 views
0

我正在尋找有關在Grape中聲明API資源路徑的語法的說明。下面的例子聲明瞭資源路徑「/ items」,「/ items /:id」,「/ objects」和「/ objects /:id」。我不明白爲什麼「/ items /:id」的定義返回null?用於在Grape中聲明資源路徑的語法

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)轉換內聯參數。

但是,你應該使用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