Acts As Keyable

Here is a simple little module for Rails apps that allow you to have prettier URLs.  By default Rails generates routes such as http://mysite.com/books/1234.  Using acts_as_keyable, this easily becomes http://mysite.com/books/oliver_twist. Place acts_as_keyable.rb in your RAILS_ROOT/lib folder and add this to your models you want to be keyable.

require 'acts_as_keyable'

class Book < ActiveRecord::Base
  acts_as_keyable :title
end

You must have a “key” attribute for the models you want to make keyable. Just add a migration.

class BookAddKey < ActiveRecord::Migration
  def self.up
    add_column(:books, :key, :string, :limit => 256)
    add_index(:books, :key)
  end

  def self.down
    remove_column(:books, :key)
  end
end

Comments welcome!

Notes

Show

Blog comments powered by Disqus