2010-10-18 49 views
14

这里是我的模型日期时间用的MongoDB/Mongoid和Rails 3未填充

include Mongoid::Document 
include Mongoid::Timestamps 

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

下面的代码是为我的形式部分代码

<%= f.label :send_at %><br /> 
<%= f.datetime_select :send_at %> 

但日期和时间是从来没有填充。 我确信Mongo和Mongoid也是最新的。 不知道是否有我丢失的东西。

[更新日志条目]

Started POST "/notifis" for 127.0.0.1 at Mon Oct 18 05:48:05 -0400 2010 
Processing by NotifisController#create as HTML 
Parameters: {"commit"=>"Create Notifi", 
"authenticity_token"=>"/hrlnvA2Xn5NqGgCkPFAQV254IHPJEvZoLxOYNNUwhc=", "_snowman"=>"☃", 
"notifi"=>{"send_at(2i)"=>"10", "is_sent"=>"0", "send_at(3i)"=>"18", 
"send_at(4i)"=>"09",  "message"=>"erwer", "send_at(5i)"=>"48", 
"send_at(1i)"=>"2010"}} 
MONGODB noti_development['notifis'].insert([{"send_at(2i)"=>"10", "created_at"=>Mon Oct 
18 09:48:05 UTC 2010, "is_sent"=>false, "updated_at"=>Mon Oct 18 09:48:05 UTC 2010, 
"_id"=>BSON::ObjectID('4cbc17d5c24d7602bc00002d'), "send_at(3i)"=>"18", 
"message"=>"Sample Message", "send_at(4i)"=>"09", "send_at(1i)"=>"2010", 
"send_at(5i)"=>"48"}]) 
Redirected to http://localhost:3000/notifis 
Completed 302 Found in 4ms 


Started GET "/notifis" for 127.0.0.1 at Mon Oct 18 05:48:05 -0400 2010 
Processing by NotifisController#index as HTML 
MONGODB 
noti_development['users'].find({:_id=>BSON::ObjectID('4cb9db18c24d7602bc000007')}, 
{}).limit(-1) 
MONGODB noti_development['notifis'].find({}, {}) 
Rendered notifis/index.html.erb within layouts/application (42.0ms) 
Completed 200 OK in 52ms (Views: 51.2ms) 
+0

请添加一些日志行,使我们可以看到,如果值正确提供给控制器。 – 2010-10-18 10:09:02

回答

8

Mongoid不处理多参数属性,如日期还没有,所以你需要做到以下几点:

# 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 

一些更多的信息在这里: http://groups.google.com/group/mongoid/browse_thread/thread/f83cbdd641581912

41

最近版本的Mongoid do处理多参数属性,你只需要包括模块模型:

include Mongoid::MultiParameterAttributes 

文档:http://mongoid.org/en/mongoid/docs/rails.html

+1

谢谢Gabe。这正是我所需要的 – 2011-12-29 02:02:44

+0

这也有助于simple_form的日期时间 – 2012-08-24 14:54:17

相关问题