27 July 2011

I've decided to use human-friendly urls (slugs) for my blog posts. I found the friendly_id gem very easy to use with Rails/ActiveRecord. Here are some of my dev notes:


The rails generate friendly_id command simply generates a migration that builds a "slugs" table:

peterkong 1.9.2@peter_blog >rails generate friendly_id
create db/migrate/20110719003359_create_slugs.rb

adding a line to Post.rb:

class Post < ActiveRecord::Base hasfriendlyid :name, :use_slug => true #########

in Rails console:

Post.create! do |post|
post.title = "my kingdom for a title!"
post.name = "petertechblog098"
post.content = "a quick brown fox"
end

<Post id: 202, name: "peter
techblog098", title: "my kingdom for a title!", content: "a quick brown fox", createdat: "2011-07-19 00:45:05", updatedat: "2011-07-19 00:45:05", creator: nil, cachedslug: "my-kingdom-for-a-title">

As you can see, friendlyid transforms your sluggable attribute - in this case "title" - into a URL-friendly string. Notice the original (!) is removed.


Your DB rows will still increment normally by id; they just will include the "sluggableid" attribute from now on. This makes friendlyid minimally invasive to your app - anything you were previously doing with id still works.


Friendlyid handles name collisions fairly well:

Post.create! do |post| post.title = "my kingdom for a title!" post.name = "petertechblog098" post.content = "a quick brown fox" end

=> http://localhost:3000/posts/my-kingdom-for-a-title--2

If you change the title, BOTH links still work:

http://localhost:3000/posts/my-kingdom-for-a-title--2
http://localhost:3000/posts/my-kingdom-for-a-title-updated

Another great thing about friendlyid is that it keeps your models at arm's length: no attributes in yours rows are modified; only the "cachedslug" attribute is added.


All slug info is contained in the Slug table:

Slug.findbysluggableid 204
=> #<Slug id: 5, name: "newest-post", sluggable
id: 204, sequence: 1, sluggabletype: "Post", scope: nil, createdat: "2011-07-19 01:23:45">
Hope that answers some questions you may have about friendly_id and friendly URLs in general. Enjoy!

blog comments powered by Disqus Back

Ustreet


Peter Kong is a
software engineer.