Avishai
Avishai

Reputation: 4762

How do you track history & activity with Mongoid?

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:

Any recommendations for libraries to use?

Thanks!

Upvotes: 2

Views: 2679

Answers (3)

Caner
Caner

Reputation: 1498

just use public activity gem. It supports rails 3 and 4 and mongoid embedded documents

Upvotes: 0

Coffee Bite
Coffee Bite

Reputation: 5164

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

Upvotes: 1

JT.
JT.

Reputation: 8066

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:

Upvotes: 0

Related Questions