Search code examples
ruby-on-railsurlslug

ID + Slug name in URL in Rails (like in StackOverflow)


I'm trying to achieve URLs like this in Rails:

http://localhost/posts/1234/post-slug-name

with both ID and slug name instead of either

http://localhost/posts/1234

or

http://localhost/posts/post-slug-name

(right now I have just slug name in URL, so this part is over). How can I do this?

UPD

I found an article on this: http://augustl.com/blog/2009/styling_rails_urls/, instead of /id/slug it suggests to use /id-slug which works perfectly for me, so I'll go with this.


Solution

  • You'll want to add a regular route with Route Globbing in addition to your resource route (assuming of course that's how your posts routes are defined). For example,

    map.resources :posts
    map.connect '/posts/:id/*slugs', :controller => 'posts', :action => 'show'