Since the beginning I always hat this one problem with rails, short urls without the controller name.
For example, I have a blog and I don’t want any dates or controller names in the url, I already have a Page model with a unique field url in my database. Rails works great with such urls:
jeena.net/pages/1
And when I modify the model I even can get it to use
jeena.net/pages/foo
But it seems not to matter what I do I can not get it to work with just:
jeena.net/foo
Of course I want the index page still to work with
jeena.net/pages
And I want creating new pages and updating old pages to work too in some was as well as the link_to()-method. All suggestions are appreciated.
To define that route, try adding the following to your routes.rb:
This will pretty much match everything to the id of your model. And that’s not very nice… You don’t want to route youe_host/pages to the pages controller, with an id equal to ‘pages’… To prevent that from happening, make sure to put that line on the end of the routes.rb file. The router uses the first route that matches the path received, so putting that line on the end of it will make sure that it will only match your route after it ran out of other meaningful options.
A better practice would be to pass regexp constraints to the router, so that it will only match ids with a specific format, like that:
Refer to the guides if you have doubts about the rails rounting system. It is pretty well written and covers lots of important things.
Rails rounting – Official Guides
edit: to create a named route, one that you can call in your controllers and override the normal routes that you are probably creating with
resource, you have to provide the:as =>parameter in your routes.rbThen you’ll be able to call it in your controller/views like this:
Hope this helps. And take a time to read the guides, it has really lots of useful info, including more details about creating named routes.