From 69e35aeb71a933e268c75c728cd51a75f39b1e1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Thalheim?= Date: Thu, 20 Nov 2014 16:40:46 +0100 Subject: [PATCH] mongoid/created_at: add setter --- ...mongoid-use-objectid-as-created-at.markdown | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/source/_posts/2013-08-23-mongoid-use-objectid-as-created-at.markdown b/source/_posts/2013-08-23-mongoid-use-objectid-as-created-at.markdown index e3d1b5d..c2381e3 100644 --- a/source/_posts/2013-08-23-mongoid-use-objectid-as-created-at.markdown +++ b/source/_posts/2013-08-23-mongoid-use-objectid-as-created-at.markdown @@ -10,24 +10,38 @@ categories: description: "Mongoid: Use ObjectId as created_at" --- +**Update: Nov 20 2014:** add setter + One great feature of Mongodb is, that the first bytes of each ObjectID contains the time, they were generated. This can be exploited to mimic the well known `created_at` field in rails. First put this file in your lib directory. + ```ruby #lib/mongoid/created.rb module Mongoid module CreatedAt - # Returns the creation time calculated from ObjectID + # Returns the creation time calculated from ObjectID # # @return [ Date ] the creation time def created_at id.generation_time end + + # Set generation time of ObjectId. + # Note: This will modify the ObjectId and + # is therefor only useful for not persisted documents + # + # @return [ BSON::ObjectId ] the generated object id + def created_at=(date) + self.id = BSON::ObjectId.from_time(date) + end end end ``` +If you are still using mongoid 3 replace `BSON::ObjectId` with `Moped::BSON::ObjectId`. + Now you can include this module in every Model, where you need created at. ```ruby @@ -37,7 +51,7 @@ class User include Mongoid::CreatedAt # ... end -u = User.new +u = User.new(created_at: 1.hour.ago) u.created_at ```