randomguy
randomguy

Reputation: 12252

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 /news/, 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.

Upvotes: 0

Views: 141

Answers (3)

esfourteen
esfourteen

Reputation: 501

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.

Upvotes: 0

doritostains
doritostains

Reputation: 1196

To change the path to a resource use :path =>

resources :news, :path => "/"

Upvotes: 2

Ryan Bigg
Ryan Bigg

Reputation: 107728

Try this at the very bottom of your routes file:

match ':id', :to => "news#show"

Upvotes: 0

Related Questions