Mongo ids leads to scary URLs

ming yeow picture ming yeow · Jan 20, 2011 · Viewed 7.7k times · Source

This might sound like a trivial question, but it is rather important for consumer facing apps

What is the easiest way and most scalable way to map the scary mongo id onto a id that is friendly?

xx.com/posts/4d371056183b5e09b20001f9

TO

xx.com/posts/a

M

Answer

kerberoS picture kerberoS · Feb 11, 2011

You can create a composite key in mongoid to replace the default id using the key macro:

class Person
  include Mongoid::Document
  field :first_name
  field :last_name
  key :first_name, :last_name
end

person = Person.new(:first_name => "Syd", :last_name => "Vicious")
person.id # returns "syd-vicious"

If you don't like this way to do it, check this gem: https://github.com/hakanensari/mongoid-slug