Git Product home page Git Product logo

mongoid-history's Introduction

Mongoid

This is the legacy fork which is no longer maintained. The official repository is now under the MongoDB organization here.

mongoid-history's People

Contributors

acant avatar aq1018 avatar bensymonds avatar cedricfung avatar cgriego avatar dblock avatar dgknght avatar edejong avatar erlingwl avatar flash73 avatar gottfrois avatar hzmangel avatar jnfeinstein avatar joelnordell avatar johnnyshields avatar matekb avatar matsprea avatar mikwat avatar msaffitz avatar nofxx avatar ojbucao avatar sarcilav avatar sbrocher avatar sivagollapalli avatar stephenhmarsh avatar vasil-nesterov avatar yads avatar zambot avatar zeitnot avatar zlw avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mongoid-history's Issues

"should undo last version when no parameter is specified" sample is not passing

I downloaded the head version, run rake and I'm getting the following failure

  1. Mongoid::History track trackables undo should undo last version when no parameter is specified
    Failure/Error: @comment.title.should == "Test3"
    expected: "Test3",
    got: "Test4" (using ==)

    ./spec/integration/integration_spec.rb:352:in `block (5 levels) in <top (required)>'

I'm using ruby 1.9.2p180 and the Gemfile.lock is https://gist.github.com/1054535

Global disabled history

Hi ,

i want to clone a model and i like to disable history in this case.
I try to use "disable_tracker" but this method is just for a Model . I want disable for global (model parent and embeds model).

How can i do this ?

Thx ,
Michael

Using STI to store versions instead of home made association

Hi!

I was wondering why you are using a single value array containing a Hash to store the historic able object (id and type) rather than using STI ?

We could then just have an 'id' and '_type' attribute referring to historic able object. It could be easy to add a dependent destroy on our models to automatically delete historic with the referenced object.

Readme mistake

Mongoid::History.tracker_class.all.each do |tracker|
  tracker.association_chain[1,-1].each do |node|
    node['name'] = node['name'].tableize
  end
  tracker.save!
end

A lil mistake here: tracker.association_chain[1,-1]. It should be tracker.association_chain[start, length] or tracker.association_chain[start..end]. In both cases i do not understand, what should happens. All the names or all names except first should be tableized? )

undefined method `create!' for Object:Class

I have a standard update action in my controller (copy-paste from the instructions), and it's throwing the following error:

Using mongoid (2.1.8)
Using mongoid-history (0.1.3)

# apartments_controller.rb
@apartment.update_attributes(params[:apartment])
# apartment.rb
include Mongoid::History::Trackable
track_history :on => :price
NoMethodError in ApartmentsController#update

undefined method `create!' for Object:Class

mongoid-history (0.1.3) lib/mongoid/history/trackable.rb:190:in `track_update'
activesupport (3.0.9) lib/active_support/callbacks.rb:415:in `_run_update_callbacks'
activesupport (3.0.9) lib/active_support/callbacks.rb:94:in `run_callbacks'
mongoid (2.1.8) lib/mongoid/persistence/modification.rb:24:in `block in prepare'
activesupport (3.0.9) lib/active_support/callbacks.rb:426:in `_run_save_callbacks'
activesupport (3.0.9) lib/active_support/callbacks.rb:94:in `run_callbacks'
mongoid (2.1.8) lib/mongoid/persistence/modification.rb:23:in `prepare'
mongoid (2.1.8) lib/mongoid/persistence/operations/update.rb:43:in `persist'
mongoid (2.1.8) lib/mongoid/persistence.rb:82:in `update'
mongoid (2.1.8) lib/mongoid/persistence.rb:144:in `upsert'
mongoid (2.1.8) lib/mongoid/persistence.rb:111:in `update_attributes'
app/controllers/apartments_controller.rb:103:in `block in update'

Doesn't work with CarrierWave fields

It would be awesome to be able to keep a history of files that has been uploaded to S3 with carrierwave. At the moment this doens't work out of the box, but I might have a go at solving it. It would mean duplicating/copying files on S3 etc. Here's a sample stacktrace if you try to include a carrierwave field in the track_history :on => [:some_carrierwave_file_field]

BSON::InvalidDocument - Cannot serialize an object of class SomeUploader into BSON.:
/Users/erlingwl/.rvm/gems/ruby-1.9.2-p290/gems/bson-1.3.1/lib/bson/bson_c.rb:24:in serialize' /Users/erlingwl/.rvm/gems/ruby-1.9.2-p290/gems/bson-1.3.1/lib/bson/bson_c.rb:24:inserialize'
......
/Users/erlingwl/.rvm/gems/ruby-1.9.2-p290/bundler/gems/mongoid-history-71394cfa4ff6/lib/mongoid/history/trackable.rb:194:in `track_update'

Why isn't mongoid-history good for use on a wiki

I note that the readme states

This is great for auditing and preventing vandalism, but is probably not suitable for use cases such as a wiki.

I would like to know why mongoid-history would not be suitable for use in a wiki?

Bug in modifier and trackable relation

When between the modifier model and trackable model you have more than one relation, when you try to write in the 'modifier' mongoid is returning the wrong relation.
I found that in mongoid/relations/bindings/referenced/in.rb the bind method is making something unexpected, it is returning for the modifier the second relation defined between the models, no the one that is created by mongoid-history in https://github.com/sarcilav/mongoid-history/blob/fixing-bug-when-trackable-modifier-has-more-than-one-relation/lib/mongoid/history/trackable.rb#L36 , I think that the problem is in the modifier you don't have to specify the relation, and it creates a weak relation.
I re-wrote two models in the integration test of mongoid-history to double check that the problem is on mongoid-history https://github.com/sarcilav/mongoid-history/blob/fixing-bug-when-trackable-modifier-has-more-than-one-relation/spec/integration/integration_spec.rb

Cannot undo creating attributes for the first time

It is not possible to undo setting a property of a document for the first time.

Document before
{
id:1
}

Document after
{
id:1
name:"foo"
}

If undoing the last change the name attribute remains in the document when it should be destroyed.

useful new feature

I miss a very useful feature to get all versions and iterate through them.

 attributes = @doc.attributes 
 arr = @doc.history_tracks.desc(:version).drop(1) 
 arr.each_with_index do |h,index| 
         arr[index + 1].nil? ? modified_keys = [] : modified_keys = arr[index + 1].modified.keys 
         attributes.update(h.original)
     print (attributes["a1"] << modified_keys.include?("a1") # show which attribute was modified.   
 end

Also I would like to filter versions of embedded documents for every parent version. It would be a good if I could define track_history with custom additional parameters and a setter.

history_tracks doesn't allow method chaining

@model.history_tracks doesn't allow method chaining because it's an array. Thus I can't do @model.history_tracks.find_by_version(params[:id]). A simple workaround is by including a custom method in my trackable model:

def versions
HistoryTracker.where(:scope => history_trackable_options[:scope], :association_chain => triverse_association_chain)
end

Looking at the source files I'm not sure why it's returning an array instead of a model to allow method chaining.

uninitialized Mongoid::Observer

Hi,

I'm getting the following error when I try to launch after implementing mongoid history:

/Users/asda/.rvm/gems/ruby-1.9.2-p290/gems/mongoid-history-0.2.1/lib/mongoid/history/sweeper.rb:2:in `module:History': uninitialized constant Mongoid::Observer (NameError)

My model:

class Item
  include Mongoid::Document
  include Mongoid::History::Trackable

  field :box_number, :type => Integer
  field :item_number, :type => Integer

  track_history :on => :all
...
end

###config/initializers/mongoid-history.rb
Mongoid::History.tracker_class_name = :history_tracker
Mongoid::History.current_user_method = :current_user

Any thoughts on what I may be missing?
Thanks!

Feature Request: Make the modifier link to ActiveRecord Users

Hi,

We have a hybrid Rails app where are users are stored in ActiveRecord in Mysql. This caused some issues because when it was trying to load the user it was using _id instead of id. Which is normal if it were stored in Mongo DB

So what i have done (in my fork) is convert the modifier in tracker to a Integer field, and then the seeker use the current_user.id to store the value.

It might break in a few other places but at the moment thats all I needed to store who made the change.

I am not sure how many people are in the same position as me, but here is my fork if anyone is interested https://github.com/mark-ellul/mongoid-history.git I have added the changes to both master and 2.4 stable branches.

This ticket is just an idea, so you can close when you have read.

weird problem caused by save modifier_id

I had a problem that caused all my older records to get "modified" by the same user regardless of the current_user. After looking around at why only older records had this behavior and new records were recording the correct modifier I discovered that the old records all had a saved "modifier_id" on the root document itself (not the history tracks, those should have it) and the new ones had nil.

That seemed to fix it. Should there be a modifier_id? I'm assuming it's not suppose to have a permanent value on the root document itself (just the history tracks)?

NoMethodError: undefined method `nil=' when using custom field

I recently customised mongoid-history so that a 'commit-msg' could be added to each history_track (see #95). This all worked well, though I seem to have discovered a bug with this custom behaviour.

@book = Book.new(:name => 'My Story', :description => 'A story about me')
@book.update_attributes(:description => 'This is a story about me and my life') #=> true
@book.history_tracks.last.undo! User.first #=> true
@book.update_attributes(:description => 'A story about me and my dog') #=> true
@book.history_tracks.last.undo! User.first
=> NoMethodError: undefined method `nil=' for #<User:0x007fd76dcbb2a8>

The error occurs when I have already successfully called an undo! on the document. With the removal of attr_accessor :commit_msg from my model, everything worked fine. I know that this custom behaviour is outside of the context of the app, but can anyone identify what is going wrong here?

undo / redo broken on embeds_one relationships (+ bug fix)

I forked the project:

https://github.com/sbrocher/mongoid-history

Added failing spec to show the bug:

sbrocher@b8faca9

And did a quick bug fix:

sbrocher@0d8a0cd

Everything is under the embeds_one branch.

My fix feels a little hackish, there may be a better way to fix this. Also, I may not have added all of the necessary tests. At any rate, I hope this helps and that the bug wasn't triggered by something else I missed.

Thanks for such an amazing gem. Please let me know if you have any questions!

Localized fields

When I destroy and restore an object with localized fields, I get something like this in them:

{"en"=>"{\"en\"=>\"SNCB RailwayNetwork\"}"}

updates no longer versioned.

I just noticed today that for the last 7 days versioning has stopped. I started to investigate to find out what went wrong but couldn't find anything. It works 100% perfectly on my local dev machine, but on heroku it is no longer recording new versions.

I have it tracking 2 different models and both fail to record versions.

I'm not even sure how to debug this? It works fine on development and I downloaded the fresh copy of the remote database. The only thing I upgraded was a version bump to the latest mongoid 3.0.13 from 0.6 or 0.8... I didn't upgrade mongoid-history, on 0.3.0... tried 0.3.1 now, same results. ;-(

Any theories? Or things I should try?

class Review
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::History::Trackable
  include Mongoid::Alize
  include Mongoid::FullTextSearch

  track_history :on => [:content, :excerpt], :track_create => true, :track_destroy => true

history_tracker.rb

class HistoryTracker
  include Mongoid::History::Tracker
end

initializer

Mongoid::History.tracker_class_name = :history_tracker
Mongoid::History.current_user_method = :current_user

My updates are not versioned (creates is working fine)

I have configured mongoid_history to track creates, updates, and deletions.

Creations are being tracked but updates are not.

I have determined that modified_attributes_for_update is always returning false.

I am tracking everything (:all) with nothing being excluded.

Modifier only changes when defined explicitly

Hi,

Let's imagine we're using mogoid-history for History Tracking on Articles and also using devise which implements current_user for the controllers.
Every time we create a new article, we need to define the modifier explicitly, for example:

def create
  @article = Article.create(params[:article].merge(modifier: current_user))
end

Now, every time we update an article, we need something similar to this:

def update
  @article = Article.find(params[:id])
  @article.update_attributes(params[:article]) # without merging current_user explicitly
end

The documentation says we don't need to define explicitly the modifier when updating attributes if we have the current_user available.
But looking at mongoid-history code itself, this is the before_create callback:

def before_create(track)
  modifier_field = track.trackable.history_trackable_options[:modifier_field]
  modifier = track.trackable.send modifier_field
  track.modifier = current_user unless modifier # this condition will always prevent a different current_user if there's a modifier already defined from the model creation
end

Is this a bug, or am I missing something?

Proposal for Better HistoryTracker storage schema

I have a use case to build a human-readable audit trail. I find the association chain syntax to be difficult to work with. I'd propose to combine :modified, :action, and :association_chain into one tree structure.

Assuming we have these models:

class Post
  ...
  field :p1
  field :p2
  embeds_many :comments
  embeds_one :section
end

class Comment
  ...
  field :c1
  field :c2
  embeds_many :links 
end

class Link
  ...
  field :l1
end

class Section
  ...
  field :s1
end

Doing an edit might generate:

modified: {
  _action: :update,
  _version: 2,
  _id: '#P1',
  p1: ___,
  p2: ___,
  comments: [{
    _id: '#C1',
    _action: :update,
    _version: 2,
    c1: ___,
    c2: ___
  },{
    _id: '#C2',
    _action: :create,
    _version: 1,
    c1: ___,
    links: [{
      _id: '#L1',
      _action: :create,
      _version: 1,
      l1: ___
    }]
  }],
  section: {
    _id: '#S2',
    _action: :delete,
    _version: 2,
    s1: ___
  }
}

If I modify only an embedded model, the audit should still save from the parent downward:

modified: {
  _action: :update,
  _id: '#P1',
  _version: 3,
  comment: [{
    _id: '#C2',
    _action: :update,
    _version: 2,
    links: [{
      _id: '#L1',
      _action: :update,
      _version: 2,
      l1: ___
    }]
  }]
}

A drawback is that this structure makes it slightly difficult to follow history on embedded models. We may want to support "breakout mode" to where you can force embedded updates to be stored on a separately from their parents (i.e. the current structure).

Support an :as option on track_history

track_history should support an :as option which will control the alias of the trackable field. This is useful if you move/rename classes, you don't have to migrate your database data.

For example:

module MyModule
  class MyClass
     include Mongoid::History::Trackable

     track_history as: 'my_class'
  end
end

I will implement this in the future (unless someone else wants to)

Setting :track_create to true fails if tracked class is a subclass of class including Trackable

I want to use STI to have several types of Elements. I want all types of elements to be tracked. Thus:

class Element
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::History::Trackable

  field :body

  track_history :on => [:body], :track_create => true, :track_destroy => true
end

class Prompt < Element
end

This fails because the track_history only includes the current class and does not search and add any subclasses. I can fix this in my app by adding this to my Element class:

def self.history_trackable_options
  super || self.superclass.send(:history_trackable_options)
end

Is this expected behavior? If not, I'll gladly work on a patch with specs.

Remove memoization

I think a lot of the memoization (at least in Trackable class) should be removed. Given that Mongoid already caches queries, I don't think it actually reduces db hits, and moreover it seems to be cleared frequently. I think it mainly adds complexity and potential for bugs. Was there a real use case for implementing it?

modifier doesn't get set when tracking creates

Using: mongoid-history-0.1.7 an mongoid 2.4.0

When creating a document the track modifier doesn't get set as the controller hasn't been setup in the sweeper (observer).

In sweeper the before sweeper method sets the controller(in turn used to set cal the current_user) however the before_create(track) gets called before the before callback.

Any thoughts on how to track the modifier when creating a document?

Support Mongoid 3.0

Hi
I would love to use it, but I followed the instructions and I can't get it to work, I added the class HistoryTracker, and I added the includes, basically I copied an pasted what the instructions show.
When i try i've : "undefined method `referenced_in' for HistoryTracker:Class"

Could you help please?

Embed all versions inside the object and Preview

Hello

Thanks for this great gem.

To make this gem more attractable is by using the same way that mongoid versioning system works which is embedding all versions inside the object.

This will increase the performance of retrieving all objects with its' versions currently what I did is duplicating the versions and embedding them inside the object but I faced a problem which I lost the ability to not use :on => :all

So, my I think you can add some features to the gem which can benefits the project is adding :excepts=>[all unversioned fields] and storing the versions inside the object itself

Also, Adding a preview option before undo or redo will be great

thanks

Trackable #original and #modified are flip-flopped for :destroy action

In trackable.rb"

      def modified_attributes_for_create
        @modified_attributes_for_create ||= attributes.inject({}) do |h,(k,v)|
          h[k] = [nil, v]
          ...
      end

      def modified_attributes_for_destroy
        @modified_attributes_for_destroy ||= attributes.inject({}) do |h,(k,v)|
          h[k] = [nil, v]
          ...
       end

modified_attributes_for_create correctly sets original: nil, modified: some_value, however, modified_attributes_for_destroy incorrectly does the same thing; I would expect it to be original: some_value, modified: nil

"Undo" and "redo" changes do not persist

I'm not sure if this is a bug, or if I'm not using this correctly. Basically, when I call @object.undo!, the appropriate fields get reverted, but the changes do not persist on @object. That is, the effects of the undo! command don't actually last.

I tried calling @object.save! after @object.undo!, but that doesn't seem to help either.

I got to the ' raise "This should never happen. Please report bug." ' part.

So this is how our database is set up:

Batch -> embeds_many Analyte
Analyte -> embeds_one RegressionEquation

We have our tracker class set up, and our association chain has the following structure (created via fabricator):

Fabricate(:calibration_audit, :association_chain => [{"name" => "Batch", "id" => @batch._id},
                                                     {"name" => "analytes", "id" => analyte._id},
                                                     {"name" => "regression_equations", "id" => "id"}])

I think it hit that line because RegressionEquation class is not embedded in the Batch class. And the current setup and tracker.rb does not handle nested embeds.

This setup worked for us when we were on 0.1.7, and we are trying to upgrade from 0.1.7 to 0.2.3, and this error popped up.

Retrieve field that has not been modified

I am trying to show pages for different versions of a document. For example I have a page that has been changed 5 times. It has a title and a content field. If I want to see what the document was like at version 2 I go to the version 2 page. However, the version 2 update only changed the content, not the title, thus the history tracker for version 2 does not have a field for title. How can I show the title of the document when it was at version 2?

Is there a way to save every attribute to the history tracker when just one of then changes?

Track some field only if condition

Hello,

is possible to track some field only if?

For example I want to track Order model, field state. I've got some states (cart, sent, in_process...) and I want to track it only if state is sent, in_process and not when it is cart.

Is possible something like this?

Changes to Tracker / Polymorphism

Before all, pardon my naiveness but why #association_chain ? Looks like just rewritting mongoid. If we just belongs_to polymorphic in the tracker, trackable just need a simple has_many, and we could also use the tracker class to implement scopes and whatnot ;)

Also, I changed modifier to be polymorphic too, we have distinct User and Client in various apps. And this way we don't even need to worry about getting the modifier_class! It'll just polymorphic work.

has_many :tracks, as: :modifier

update_all support

Right now update_all seems to ignore all history tracking. Is support for tracking update_all planned? or is this a known limitation that could be documented?

class Post
  include Mongoid::Document
  include Mongoid::History::Trackable
  field           :title
  track_history
end

Post.create!(title: 'First Title')
Post.first.title #=> 'First Title'
Post.first.history_tracks.count #=> 0

Post.update_all(title: 'Second Title')
Post.first.title #=> 'Second Title'
Post.first.history_tracks.count #=> 0

Mongoid Version 3.1 compatibility issue

I have tried mongoid-history with mongoid 3.1.2 but it complain about its dependency on mongoid 3.0 !

Bundler could not find compatible versions for gem "mongoid":
In Gemfile:
mongoid-history (>= 0) java depends on
mongoid (~> 3.0.4) java

mongoid (3.1.2)

Default version field name should be "_version".

Hi !

As version field is a meta-field, I think this field's name should defaults to _version, the same way Mongoid adds its own meta-fields (_id, _type).

I know this field name can be overridden, but, I think, default values should respect best conventions.

Regards,
Gauthier.

Move common mongoid-history code to lib

I am using mongoid-history to track several models, thus I have common code across multiple models. I am trying to move this common code into the lib directory:

# lib/history.rb
module History
  include Mongoid::History::Trackable
  track_history   :on => [:content]
end
# models/my_model.rb
Class MyModel
  include Mongoid::Document
  include History
end
undefined method `collection_name' for History:Module

Is there anyway to achieve this?

Get current_user in Sinatra?

Is it possibile to grab request details from a request in Sinatra. The sweeper observer doesn't seem to work for sinatra.

I have an api which receives an id of the user. I am adding an additional field to tracker, and I want a way to access the request to pull out that info.

Any help would be great!

Mongoid-history compatibility issue with Rails 4.1.0.rc1

Hi, bundle install cannot solve the following dependency.

Bundler could not find compatible versions for gem "activemodel":
In Gemfile:

mongoid-history (>= 0) ruby depends on
  activemodel (~> 3.0) ruby

rails (~> 4.1.0.rc1) ruby depends on
  activemodel (4.1.0.rc1)

Expected ... to define error (in Mongoid 3.x support)

Hi everybody

i always get the following error...

Expected xxx/app/models/core/models/base.rb to define Core::Models::Base

The file exists and looks like

module Core
  module Models
    class Base
      include Mongoid::Document

      # @!attribute created_at
      # @!attribute updated_at
      include Mongoid::Timestamps

      after_initialize :defaults

      private
      def defaults

      end
    end
  end
end

Any ideas?

Does this works with Mongoid 2.1.7?

I would love to use it, but I followed the instructions and I can't get it to work, I added the class HistoryTracker, and I added the includes, basically I copied an pasted what the instructions show, when I call "source.history_tracks" in console, I get

NoMethodError: undefined method `where' for Object:Class

Could you help please?

README correct?

According to README.rdoc:

track = comment.history_tracks.last

track.undo! # comment title should be "Test"

track.redo! # comment title should be "Test 2"

But when I try it I get:

ruby-1.9.2-p180 :004 > track.undo!
ArgumentError: wrong number of arguments (0 for 1)
from /home/reed/.rvm/gems/ruby-1.9.2-p180@clinical-trials/gems/mongoid-history-0.1.4/lib/mongoid/history/tracker.rb:20:in `undo!'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.