我有一个索引的集合:created_at(在这个特殊情况下应该是一个日期)
从rails中保存条目然后按日期检索它的正确方法是什么?
我正在尝试这样的事情:
型号: field:created_at,:type =>时间
脚本:
Col.create(:created_at => Time.parse(another_model.created_at).to_s
和
Col.find(:all,:conditions => {:created_at => Time.parse(同样的东西)})
并且它没有返回任何内容
答案 0 :(得分:3)
Mongo驱动程序和各种ORM处理Date,Time和DateTime对象就好了;没有理由把它们变成字符串。
Col.create(:created_at => another_model.created_at)
找到:
Col.all(:created_at => another_model.created_at)
您不希望设置字符串,因为日期在内部存储为BSON Date对象,并且如此索引和搜索。如果将它们保存为字符串,则无法有效地执行大于/小于/范围比较的操作。
答案 1 :(得分:1)
Col.create(:created_at => Time.parse(another_model.created_at).to_s)
该行将您的时间对象作为String传递,取消to_s
将其作为Time对象发送到ORM(MongoMapper或Mongoid)中的类型解析层。这是我能看到的唯一一个会导致它无效的错误。