Skip to content
Drop-in solution to pretty urls when using Mongoid
Pull request Compare This branch is even with crowdint:master.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.



Whenever you use MongoDB and Mongoid, there's a high chance you will end up preparing your urls with a slug instead of the traditional ids because MongoDB ids are ugly.

This gem will help you generate slugs in an easy way


So far it works with the Rails 3 version of Mongoid.


If you're using mongoid 2.0.0.rc.7 or less, you need to use version 0.0.5

When mongoid 2.0.0.rc.8 was released there was a change that prevented backwards compatibility.


Rails 3

Include it in your Gemfile:

gem 'slugoid'

And run bundler

bundle install


To use it, all you have to do is call acts_as_slugoid in your Mongoid::Document

class Project
  include Mongoid::Document


By default, this will declare a field on the Document called :slug and will try to generate the slug from a field called :name.



If you want to change the field to generate the slug you can use the :generate_from option:

class Organization
  include Mongoid::Document

  field :alternative_name
  acts_as_slugoid :generate_from => :alternative_name

This will generate the slug form a field called :alternative_name.


If you want to change the field where the slug is stored you can use the :store_as option:

class Organization
  include Mongoid::Document

  field :name
  acts_as_slugoid :store_as => :alternative_slug

Now it will store the slug in a field called :alternative_slug. If the specified field is not defined on the Document it will be automatically declared, so adding:

field :alternative_slug

is optional.


To make things transparent and easy, by default, the find method of the acts_as_slugoid Documents will look for the object by the slug, not the id.

So, if you had the Project class configured as the example above:

@project = Project.create(:name => "Name")

Project.find(@project.to_param)                               #=> @project

If, for any reason, you have to look for the object using its id, you have to be explicit:

@project = Project.create(:name => "Name")

Project.find(:first, :conditions => {:_id =>})    #=> @project
Project.where(:_id =>                            #=> @project

The find behavior for the other Mongoid::Documents remains the same.

About the Author

Crowd Interactive is an American web design and development company that happens to work in Colima, Mexico. We specialize in building and growing online retail stores. We don’t work with everyone – just companies we believe in. Call us today to see if there’s a fit. Find more info here!

Something went wrong with that request. Please try again.