DateTime with MongoDB/Mongoid and Rails 3 Not Populating

前端 未结 2 1700
广开言路
广开言路 2021-02-04 08:08

Here is the code in my Model

 include Mongoid::Document
 include Mongoid::Timestamps

 field :message, :type => String
 field :send_at, :type => DateTime
<         


        
相关标签:
2条回答
  • 2021-02-04 08:23

    Recent versions of Mongoid do handle multi-parameter attributes, you just have to include the module in your model:

    include Mongoid::MultiParameterAttributes
    

    Docs: http://mongoid.org/en/mongoid/docs/rails.html

    0 讨论(0)
  • 2021-02-04 08:31

    Mongoid does not handle multiparameter attributes like Date yet, so you need to do the following:

    # copied from: https://gist.github.com/315227
    # add this to a new file in your lib directory
    module MultiParameterAttributes
      def filter_time(attributes, name)
         attrs = attributes.collect do |key, value|
           if key =~ /^#{Regexp.escape(name.to_s)}\((\d+)(\w)\)$/
             [$1.to_i, value.send("to_#$2")]
           end
         end.compact.sort_by(&:first).map(&:last)
         Time.zone.local(*attrs) unless attrs.empty?
      end
    end
    
    # include the module above in your application_controller.rb
    class ApplicationController < ActionController::Base
      include MultiParameterAttributes
    end
    
    # and in the controller action where you process the form params, use filter_time
    class YourController < ApplicationController
      def your_action
        time = filter_time(params, :my_time_attribute_name)
      end
    end
    

    Some more info here: http://groups.google.com/group/mongoid/browse_thread/thread/f83cbdd641581912

    0 讨论(0)
提交回复
热议问题