rod mclaughlin


Meaningful URLs in Rails (13 mar 10)

You know how online article urls used to be like this

http://mywhatever.com/articles/98z/345d-5567e-f0ff?

then they became more like

http://mywhatever.com/dallas-are-not-going-to-the-superbowl ?

Well, I just changed my Rails apps so they do this. It took less than a day.

http://rubyjunction.us/articles/20

still works but

http://rubyjunction.us/will-obama-close-cia-secret-prisons-

is more meaningful.

The key is this, in routes.rb

map.connect ':url_title',
     :controller => 'articles',
     :action => 'title_url'

which must be below the other routes, this in article.rb

def url_title
     title.gsub( /[^A-Za-z0-9]/, '-' ).downcase
end


and this in articles/index.html.erb

<a href="/<%= article.url_title %>"><%=h article.title %></a>



Back
Portland London