【问题标题】:mongo_mapper_acts_as_versioned failing when saving a Time typemongo_mapper_acts_as_versioned 保存时间类型时失败
【发布时间】:2012-05-30 21:06:06
【问题描述】:

我正在尝试使用我分叉的https://github.com/Bramanga/mongo_mapper_acts_as_versioned gem 在我的 mongomapper 模型上设置版本控制。但是,每当我尝试保存我的 Finding 模型时,如果我尝试使用 Time 类型保存它就会失败(我必须使用它,因为 MongoDB 只支持 utc 时间,而不支持日期)。

型号:

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

终端输出:

加载开发环境(Rails 3.0.10)

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

=>

[2] pry(main)>find.save

=> 是的

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

=>“2012 年 12 月 24 日”

[4] pry(main)>find.save

BSON::InvalidDocument:当前不支持 ActiveSupport::TimeWithZone;请改用 UTC 时间实例。 来自/home/bramanga/.rvm/gems/ruby-1.9.2-p290@actionlog/gems/bson-1.6.2/lib/bson/bson_c.rb:24:in `serialize'

我不确定如何解决这个问题。也许我只是做错了。有什么想法吗?

【问题讨论】:

  • 如果我注释掉“plugin”和“many”行,你的代码行对我有用,所以我真的没有测试 MongoMapper::Acts::Versioned 是否与你的问题有关。您可以发布您的 Gemfile 吗?猜测您正在使用的 gem 和插件既困难又耗时。

标签: ruby-on-rails ruby-on-rails-3 mongomapper bson rails-3.0.10


【解决方案1】:

在分叉回购后修复了我自己的问题。我的解决方案是here

问题与mongodb 支持的日期类型有关。它只支持UTC 时间戳格式。我添加了自己的 escape_mongo 方法,在持久化到数据库之前转换为安全的 timestamp 类型:

def escape_mongo(obj)       
    obj.is_a?(Date) || obj.is_a?(Time) ? Date.to_mongo(obj) : obj   
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    • 2011-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多