Skip to content

Instantly share code, notes, and snippets.

@veesahni
Created August 12, 2011 22:40
Show Gist options
  • Save veesahni/1143152 to your computer and use it in GitHub Desktop.
Save veesahni/1143152 to your computer and use it in GitHub Desktop.
auto incrementing id w/ mongoid
# I strongly suggest using object id's instead of auto incrementing id's
# but since you're here, I'm assuming you've already got your heart set!
# First, create a counter via mongodb console
db.counter.insert({_id:"something",count:0})
# Now, automatically use the counter on save
class Something
include Mongoid::Document
include Mongoid::Timestamps
before_save :set_id
def set_id
if self.id.class == BSON::ObjectId
counter = Mongoid.database["counters"].find_and_modify(
:query => { "_id" => "something" },
:update => { "$inc" => {"count" => 1} })
self.id = Integer(counter["count"])
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment