What do you think is the best way to create SEO friendly URLs (dynamically) in Rails?

+5  A: 

Override the to_param method in your model classes so that the default numeric ID is replaced with a meaningful string. For example, this very question uses best-permalinking-for-rails in the URL.

Ryan Bates has a Railscast on this topic.

John Topley

Check out the permalink_fu plugin (extracted from Mephisto)... the Git repository is located here.

+3  A: 

ActiveSupport has a new method in Rails to aid this - String#parameterize. The relevant commit is here; the example given in the commit message is "Donald E. Knuth".parameterize => "donald-e-knuth"

In combination with the to_param override mentioned by John Topley, this makes friendlier URLs much easier.

Ben Scofield
+1  A: 

rsl's stringex is pretty awesome, think of it as permalink_fu done right.

Ryan Bigg
+1  A: 

I largely use to_param as suggested by John Topley.

Remember to put indexes such that whatever you're using in to_param is quickly searchable, or you'll end up with a full table scan on each access. (Not a performance-enhancer!)

A quick work-around is to put the ID somewhere in there, in which case ActiveRecord will ignore the rest of it as cruft and just search on the id. This is why you see a lot of Rails sites with URLs like .

For more detail on this and other SEO observations from my experience with Rails, you may find this page on my site useful.

Patrick McKenzie
+1  A: 

For me friendly_id works fine, it can generate slugs too, so You don't need to matter about duplicated urls, scopes are also supported.


I have made a small and simple gem which makes it easier to override the to_param method. It can be found here.

Thorbjørn Hermansen