开发者

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:

  • Updating objects (Mike changed the price from 50 to 75)
  • Creati开发者_如何转开发ng 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!


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
  • state_machine
  • mongoid observers - what callbacks Mongoid provides for Observers


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜