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

59 lines
1.3 KiB
Markdown
Raw Normal View History

---
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"
---
2014-11-20 15:40:46 +00:00
**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.
2014-11-20 15:40:46 +00:00
```ruby
#lib/mongoid/created.rb
module Mongoid
module CreatedAt
2014-11-20 15:40:46 +00:00
# Returns the creation time calculated from ObjectID
#
# @return [ Date ] the creation time
def created_at
id.generation_time
end
2014-11-20 15:40:46 +00:00
# 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
```
2014-11-20 15:40:46 +00:00
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
#app/models/user.rb
class User
include Mongoid::Document
include Mongoid::CreatedAt
# ...
end
2014-11-20 15:40:46 +00:00
u = User.new(created_at: 1.hour.ago)
u.created_at
```
That's all easy enough, isn't it?