How to do this with routing in Rails?
Say we have a simple resource called news:
resources :news
The generated paths are in this form /news/:id
. I would like to provide a shortcut for this by dropping the /开发者_如何学Gonews/, so that /1/ goes to news#show with id 1 and the same for all the other resourceful actions of news.
I figured it's probably something along the lines of
match '/:id(/:action)', :controller => 'news'
but this isn't working.
To change the path to a resource use :path =>
resources :news, :path => "/"
Try this at the very bottom of your routes file:
match ':id', :to => "news#show"
Placing a custom route at the bottom of your routes.rb should work, that will give it lowest priority and allow valid routes to work first:
match '/:id', :to => 'news#show'
It's important to note that this will basically route anything that wasn't previously caught, and does not exist as an actual static file, to that controller/action. You will want to make sure you render your 404 error page if the news record does not exist.
精彩评论