Mongoid日期(DateTime)字段无法正确解析以存储到数据库中

|| 我已经遇到这个问题好几天了,却找不到任何解决方案。看来我无法更改Mongoid文档中字段的日期(&DateTime)格式
class Project
  include Mongoid::Document

  field :deadline, :type => Date
end
然后我可以像这样分配日期:
p = Project.new
p.deadline = \"20-10-2011\"
但是我不能以其他格式分配:
p.deadline = \"20/10/2011\"
ArgumentError: invalid date
    from /Users/pww/.rvm/rubies/ree-1.8.7-2011.03/lib/ruby/1.8/date.rb:956:in `new_by_frags\'
    from /Users/pww/.rvm/rubies/ree-1.8.7-2011.03/lib/ruby/1.8/date.rb:1000:in `parse\'
    from /Users/pww/.rvm/gems/ree-1.8.7-2011.03@v3/gems/mongoid-2.0.2/lib/mongoid/extensions/date/conversions.rb:18:in `convert_to_time\'
    from /Users/pww/.rvm/gems/ree-1.8.7-2011.03@v3/gems/mongoid-2.0.2/lib/mongoid/extensions/time_conversions.rb:6:in `set\'
    from /Users/pww/.rvm/gems/ree-1.8.7-2011.03@v3/gems/mongoid-2.0.2/lib/mongoid/field.rb:109:in `set\'
    from /Users/pww/.rvm/gems/ree-1.8.7-2011.03@v3/gems/mongoid-2.0.2/lib/mongoid/attributes.rb:182:in `typed_value_for\'
    from /Users/pww/.rvm/gems/ree-1.8.7-2011.03@v3/gems/mongoid-2.0.2/lib/mongoid/attributes.rb:96:in `write_attribute\'
    from /Users/pww/.rvm/gems/ree-1.8.7-2011.03@v3/gems/mongoid-2.0.2/lib/mongoid/fields.rb:161:in `deadline=\'
    from (irb):11
我尝试以几种方式更改Mongoid日期的默认格式,包括
Date::DATE_FORMATS[:default] = \"%d/%m/%Y\"
确实可以显示该格式的数据,但不能以该格式存储数据。我尝试使用本地化文件,如下所示:
date:
    formats:
      default: \"%d/%m/%Y\"
      short: \"%b %d\"
      long: \"%B %d %Y\"
它也不起作用。我可能不知道如何正确处理它,但这可能是Mongoid的问题。 我在用:
Mongoid (2.0.2)
Rails (3.0.6)
ree (1.8.7-2011.03)
我知道这个(https://github.com/mongoid/mongoid/issues/53),这更是一个Date时区问题。 任何帮助和信息,将不胜感激。 谢谢。     
已邀请:
        如果该属性定义为日期,则需要有效的Date对象。 您应该负责解析值和分配日期。
p = Project.new
p.deadline = Time.Time.strptime(\"20/10/2011\", \"%d/%m/%Y\")
    
        实际上,我已经通过元编程为Date字段重新定义了setter方法,从而设法做到了半自动
    #this returns all the Date fields as an array
    def self.date_fields
    self.fields.map {|f,v| f if v.type == Date}.compact

    end


    def self.convert_dates 

    #go through all the fields and define a method for each
    self.date_fields.each  do |f|

    define_method \"#{f}=\".intern do |arg|

    #if there is a value
    if arg.present?   
    begin
     #try to parse it the normal d/m/Y way
      new_date =Date.parse(arg)

    rescue
      #if it fails attempt the US format. Could add more formats by nesting 
      #rescues
      new_date = DateTime.strptime(arg, \'%m/%d/%Y\')
    end
      #call super to let Mongoid handle it
    super(new_date)
    end
    end
    end
将在您的initialize方法中调用convert_dates(我正在使用自定义类工厂)     
        因为字段:deadline,:type => Date会生成时间类型而不是日期类型的对象。您可以在Rails控制台中使用
p.deadline.is_a? Date
将产生FALSE,but9ѭ将产生true, 通过将您的Mongoid更新到最新版本来解决此问题
gem \'mongoid\', :git => \"git://github.com/mongoid/mongoid.git\"
    
        像这样解决它:
  # our form sends in month, day, year
  def my_date=(*args)
    if args.first.is_a?(String)
      args[0] = Time.strptime(args[0], \"%m/%d/%Y\")
    end
    super(*args)
  end
    

要回复问题请先登录注册