如何在Rails中命名嵌套路由参数?

时间:2018-01-15 13:40:57

标签: ruby-on-rails rails-routing

我有以下嵌套路线:

resources :carts, only: [:show, :update, :create], param: :token do
  resources :items, :controller => :cartitems, except: [:new, :edit], param: :product_id
end

这会生成

GET    /api/merchants/:merchant_id/carts/:cart_token/items(.:format)             cartitems#index
POST   /api/merchants/:merchant_id/carts/:cart_token/items(.:format)             cartitems#create
GET    /api/merchants/:merchant_id/carts/:cart_token/items/:product_id(.:format) cartitems#show
PATCH  /api/merchants/:merchant_id/carts/:cart_token/items/:product_id(.:format) cartitems#update
PUT    /api/merchants/:merchant_id/carts/:cart_token/items/:product_id(.:format) cartitems#update
DELETE /api/merchants/:merchant_id/carts/:cart_token/items/:product_id(.:format) cartitems#destroy
...

我想删除resources :items参数中的控制器部分。这意味着:我想将:cart_token参数重命名为:token。就像:

GET    /api/merchants/:merchant_id/carts/:token/items(.:format)             cartitems#index
POST   /api/merchants/:merchant_id/carts/:token/items(.:format)             cartitems#create
GET    /api/merchants/:merchant_id/carts/:token/items/:product_id(.:format) cartitems#show
PATCH  /api/merchants/:merchant_id/carts/:token/items/:product_id(.:format) cartitems#update
PUT    /api/merchants/:merchant_id/carts/:token/items/:product_id(.:format) cartitems#update
DELETE /api/merchants/:merchant_id/carts/:token/items/:product_id(.:format) cartitems#destroy
... 

如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

不知道这是否是最佳方式,但我得到了你期望的路线:

scope 'api/mechantes/:merchant_id/carts/:token' do
  resources :items, :controller => :cartitems, except: [:new, :edit], param: :product_id
end

希望这可以有所帮助。祝你好运!