← back to the blog
fousa blog
Clean URL's in Rails
Another great and awesome informational article by me!
PROBLEM
When you create a new model (for example Post) you'll also have a posts_controller. This controller will be called from following URL: /posts/.
But because I like clean URL's, I prefer it to be called /blog/.
SOLUTION
What I certainly don't want to do is change the name of the controller... I prefer to do this otherwise... Behold!
Add the line below to your routes.rb
map.resources :posts, :as => "blog"This will enable the URL /blog/. All your generated post paths (like posts_path) will use the new posts name (blog that is).
Will /posts/ still work?
Off course! And you can put both resource lines in your routes.rb. The first one will be the default used!
map.resources :posts, :as => "blog" map.resources :postsIn this case posts_path will show /blog/.
map.resources :posts map.resources :posts, :as => "blog"Now posts_path will show /posts/.
This can be very handy when you are not satisfied with you URL's.
Send me some feedback!
Just a short note for later reference, this has been changed in Rails 3 (beta 3). It boils down to this: you need to replace :as with :path from now on.
written by Simon → 4 months ago