You should use an already existent gem for this case. The friendly_id gem provides the functionality you are looking for. Check their guide for more information about to setup and use.
For a simple example, as taken from here:
in your model:
class Post < ActiveRecord::Base
attr_accessible :content, :title
extend FriendlyId
friendly_id :title, use: :slugged
end
then create a migration:
$ rails g migration add_slug_to_posts slug:string
$ rake db:migrate
and fill it:
class AddSlugToPosts < ActiveRecord::Migration
def change
add_column :posts, :slug, :string
add_index :posts, :slug
end
end