Skip to content

Instantly share code, notes, and snippets.

@regdog
Forked from veesahni/gist:1143152
Created July 23, 2013 03:26
Show Gist options
  • Save regdog/6059640 to your computer and use it in GitHub Desktop.
Save regdog/6059640 to your computer and use it in GitHub Desktop.
# 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