如何在rails嵌套资源中创建干净的URL?

时间:2014-12-12 07:05:52

标签: ruby-on-rails ruby-on-rails-3 postgresql

我有两个控制器StoresStocks,这两个控制器的路由如下:

  resources :stores do
    resources :stocks,param: :product_id,:only=>[:index] do
      get '/:product_id', to: 'stocks#index'
    end
  end

rake routes之后,我得到的路径如下:

GET /stores/:store_id/stocks/:stock_id/:product_id(.:format)

但我想从该路径中删除:stock_id,以便生成的路径为:

GET /stores/:store_id/stocks/:product_id(.:format)

如果可能的话请帮助。

1 个答案:

答案 0 :(得分:1)

试试这个:

resources :stores do
  resources :stocks, except: :index do
    get '/:product_id', to: 'stocks#index', on: :collection
  end
end

这会给你:

GET  /stores/:store_id/stocks/:product_id(.:format)   stocks#index

如果您还想要默认索引操作,那么:

resources :stores do
  resources :stocks do
    get '/:product_id', to: 'stocks#index', on: :collection
  end
end

这将为您提供索引:

              GET  /stores/:store_id/stocks/:product_id(.:format)  stocks#index
store_stocks  GET  /stores/:store_id/stocks(.:format)              stocks#index