blog/source/_posts/2013-08-23-mongoid-use-objectid-as-created-at.markdown

45 lines
911 B
Markdown

---
layout: post
title: "Mongoid: Use ObjectId as created_at"
date: 2013-08-23 07:34
comments: true
categories:
- mongodb
- rails
- mongoid
description: "Mongoid: Use ObjectId as created_at"
---
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
#
# @return [ Date ] the creation time
def created_at
id.generation_time
end
end
end
```
Now you can include this module in every Model, where you need created at.
```ruby
#app/models/user.rb
class User
include Mongoid::Document
include Mongoid::CreatedAt
# ...
end
u = User.new
u.created_at
```
That's all easy enough, isn't it?