Question: I'm building a Rails app that uses MongoDB as the backend, with Mongoid as the ODM. I've found it very useful, but I'm looking for a good way to keep track of the following:

* Updating objects (Mike changed the price from 50 to 75)
* Creating objects (Dan added a comment on Mike's post)
* Basic stats (Mike's post was viewed 10 times and edited 3 times)

Any recommendations for libraries to use?

Thanks!

Answer: 
Try the mongoid-history and trackoid gems. The first allows you to track changes and the latter allows you to track activity.

<https://github.com/aq1018/mongoid-history>

<https://github.com/twoixter/trackoid>
There are several options you have. Here are a couple things to keep in mind:

* Mongoid has a versioning plugin where you can keep track of versions of a document
* You can create an embedded document to store notes/changes on a model. Use an observer to add a note when certain things happen. You can tie this note to the document version if you'd like.

I have a case where I'm using an embedded Note object to track the state and progression of an order. Here's a rough outline of what I did:

```
class Order
  include Mongoid::Document
  include Mongoid::Paranoia
  include Mongoid::Timestamps
  embeds_many :notes, as: :notable
  # fields
end

class Note
  include Mongoid::Document
  include Mongoid::Timestamps

  field :message
  field :state
  field :author

  #(I can add notes to any Model through :notable)
  embedded_in :notable, polymorphic: true 
end

```

Then I created an observer to track state changes in Order:

```
class OrderObserver < Mongoid::Observer
  def after_transition(order, transition)
    order.notes.build(state: transition.to)
  end
end

```

`after_transition` is a callback that the state machine plugin provides. If you don't care about integrating a state machine, you can just use Mongoid-provided callbacks like `after_save`, `after_update`, `around_update`, etc.

Each time I transition through the states of an Order, I get a new timestamped note that records the history of each transition. I've left a lot of implementation details out, but it's working well for me so far.

Links:

* [mongoid extras](http://mongoid.org/docs/extras.html)
* [state\_machine](http://github.com/pluginaweek/state_machine)
* [mongoid observers](http://mongoid.org/docs/callbacks/observers.html) - what callbacks Mongoid provides for Observers