0

I am trying to set up versioning on my mongomapper model using the https://github.com/Bramanga/mongo_mapper_acts_as_versioned gem that I forked. However, whenever I try to save my Finding model, it fails if I try to save it with a Time type (which I have to use because MongoDB only supports utc times, and not dates).

Model:

class Finding
  require 'carrierwave/orm/mongomapper'
  include MongoMapper::Document
  ensure_index 'finding.document'
  plugin MongoMapper::Acts::Versioned 

  attr_accessible :found_date, :target_date, :abated_date

  key             :found_date,          Time
  key             :target_date,         Time
  key             :abated_date,         Time
  
  belongs_to      :client
  many            :uploads, :dependent => :destroy
  many            :documents, :dependent => :destroy

  timestamps!

  def found_date=(date)
    if date.present?
      self[:found_date] = Chronic.parse(date).utc.beginning_of_day
    else
      self[:found_date] = nil
    end
  end

  def target_date=(date)
    if date.present?
      self[:target_date] = Chronic.parse(date).utc.beginning_of_day
    else
      self[:target_date] = nil
    end
  end

  def abated_date=(date)
    if date.present?
      self[:abated_date] = Chronic.parse(date).utc.beginning_of_day
    else
      self[:abated_date] = nil
    end
  end
end

Terminal output:

Loading development environment (Rails 3.0.10)

1 pry(main)> finding = Client.first.findings.build

=> <#Finding _id: BSON::ObjectId('4fc67c8f4e484f267c000002'), client_id: BSON::ObjectId('4f7119884e484f25bd005ee8'), custom_fields: {}, legacy_attachments: [], tags: []>

[2] pry(main)> finding.save

=> true

[3] pry(main)> finding.found_date = "12/24/2012"

=> "12/24/2012"

[4] pry(main)> finding.save

BSON::InvalidDocument: ActiveSupport::TimeWithZone is not currently supported; use a UTC Time instance instead. from /home/bramanga/.rvm/gems/ruby-1.9.2-p290@actionlog/gems/bson-1.6.2/lib/bson/bson_c.rb:24:in `serialize'

I'm not sure how to fix this. Maybe I'm just doing it wrong. Any ideas?

Community
  • 1
  • 1
Bramanga
  • 138
  • 1
  • 10
  • Your code lines work for me if I comment out the "plugin" and "many" lines, so I really haven't tested whether MongoMapper::Acts::Versioned is related to your problem. Can you post your Gemfile? It's difficult and time consuming to guess at the gems and plugins that you are using. – Gary Murakami Jun 10 '12 at 01:58

1 Answers1

2

Fixed my own issue after forking the repo. My solution is here.

The issue is related to mongodb's supported date types. It only supports a UTC timestamp format. I added my own escape_mongo method to convert to a safe timestamp type before being persisted to the database:

def escape_mongo(obj)       
    obj.is_a?(Date) || obj.is_a?(Time) ? Date.to_mongo(obj) : obj   
end
Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107
Bramanga
  • 138
  • 1
  • 10