-
-
Save regdog/6059640 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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