创建使用ID以外的其他属性的路由非常简单。 FriendlyID大出的现成的解决方案,但它只会让你看起来像网址:
/categories/lamas/categories/maintenance/products/lama-polish
创建网址的如lamas/maintenence/lama-polish
绝对是可能的,但会因为它不是传统的困难,而且也有很多潜在的隐患。
例如,你可以在开始时:
resources :categories, path: '/' do
resources :categories, path: '' do
# resources :products
end
end
,这将创造:
Prefix Verb URI Pattern Controller#Action
category_categories GET /:category_id(.:format) categories#index
POST /:category_id(.:format) categories#create
new_category_category GET /:category_id/new(.:format) categories#new
edit_category_category GET /:category_id/:id/edit(.:format) categories#edit
category_category GET /:category_id/:id(.:format) categories#show
PATCH /:category_id/:id(.:format) categories#update
PUT /:category_id/:id(.:format) categories#update
DELETE /:category_id/:id(.:format) categories#destroy
categories GET / categories#index
POST / categories#create
new_category GET /new(.:format) categories#new
edit_category GET /:id/edit(.:format) categories#edit
category GET /:id(.:format) categories#show
PATCH /:id(.:format) categories#update
PUT /:id(.:format) categories#update
DELETE /:id(.:format) categories#destroy
但后来有一个超大型的疑难杂症 - 让我们说的请求是
GET /lamas/joe-the-lama
Rails应该如何知道这个需求est应该由LamasController
处理,而不是CategoriesController
?你将不得不为两者做一个数据库查询。当然这不是问题,如果你总是有两个类别,但你得到了我的漂移 - 事情会变得复杂得很快。
标准的Rails风格安静的路由可能有点罗嗦,但它确实避免了很多潜在的歧义。
来源
2015-06-18 18:59:46
max
你可能要看看[** friendly_id **](https://github.com/norman/friendly_id) – Pavan
[This SO question](http://stackoverflow.com/questions/7735315/rails-路由到用户名,而不是ID)也非常类似于你的。 'friendly_id'或'to_param'是两种不同的方式来处理它。 – sjagr
谢谢你们的伟大建议。我不知道这些宝石。 – greyoxide