你如何在 Grape 中获得多个路线参数以在 Grape 中工作?
我可以使这条路线工作:
.../api/company/:cid
但是当我尝试这个时:
.../api/company/:cid/members
.../api/company/:cid/members/:mid
我收到错误。
这是有效的代码。
resource 'company' do
params do
optional :start_date, type: Date, desc: "Start date of range."
optional :end_date, type: Date, desc: "End date of range."
end
route_param :cid do
get do
{company_id: params[:cid]}
end
end
最佳答案
class API::Company < Grape::API
resource :company do
route_param :cid do
desc "GET"
params do
# your params
end
get '/' do # => '.../api/company/:cid
# process get
end
resources :members do
desc "GET"
params do
# your params
end
get '/' do # => '.../api/company/:cid/members/'
# process get
end
route_param :mid do
desc "GET"
params do
# your params
end
get '/' do # => '.../api/company/:cid/members/:mid'
# process get
end
end
end
end
end
end
你可以那样做。或者您可以创建两个不同的资源文件并将成员挂载到公司。像这样:
# api/company.rb
class API::Company < Grape::API
resource :company do
route_param :cid do
desc "GET"
params do
# your params
end
get '/' do # => '.../api/company/:cid
# process get
end
mount API::Members
end
end
end
# api/member.rb
class API::Member < Grape::API
resources :members do
desc "GET"
params do
# your params
end
get '/' do # => '.../api/company/:cid/members/'
# process get
end
route_param :mid do
desc "GET"
params do
# your params
end
get '/' do # => '.../api/company/:cid/members/:mid'
# process get
end
end
end
希望有帮助
关于ruby - Grape 中的多个路由参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21177622/