0

Rails ~ 4.2.1

Mongoid ~ 4.0.2

in _form.html.erb, the code looks like this:

<%= form_for @workout %>
  <%= f.label :date%>
  <%= f.datetime_select :date>
  <%= f.submit %>
<% end %>

in Workout.rb, the code looks like this:

class Workout
  include Mongoid::Document
  field :date, type: DateTime
end

I naively thought The View could send {"workou[date]" => "2015/06/20 10:10"} to the Controller, but actually, it sent {"workout[date(1i)]" => "2015", workout[date(2i)] => "06", ... workout[date(5i)] => "10"}. In the end, in Mongo workout collection, it stored the time separately.

I want Mongo DB to store them in one field, type as DateTime. How can I achieve that?

nesiseka
  • 1,268
  • 8
  • 22
mCY
  • 2,731
  • 7
  • 25
  • 43

1 Answers1

0

You ask for Datetime, but maybe my answer (using Date type) can lead you the way too. Let's see.

This answer suggests the Best way to store date/time in mongodb. That is if you can you should choose native JavaScript Date objects.

The way I solve my issue (with Date object) was as follows.

I use the Date field type in my models. E.g. the Event model has two date types, from_date and end_date.

In the controller (e.g. new method) you can use the Date object as usual, no special treatment in my case. I guess for you it is the same. E.g. Date.current or Date.current+3.days. Note the create method does not specifically manipulate Date objects. The parameters from the web view form are taken as is.

In the view I use the date_field helper. It is an input field of type date. Note that currently Google Chrome supports the date field type, so you will see a date picker pop up. Other browsers don't support the field yet, so it is a simple input field for them. I use jQuery Datepicker in case the browser does not support the input date type field, e.g.

$(document).ready(function(){
    ...
    if ( $('[type="date"]').prop('type') !== 'date' ) {
        $('input[type="date"]').datepicker({dateFormat: "yy-mm-dd"});
    }
    ...
});

So in your case maybe you could do something analogue to that solution. Probably there is no datetime_field helper method, but a simple input field could do and you use JS to ensure you are saving a native JS Date/Datetime object for the corresponding field.

Community
  • 1
  • 1
Ely
  • 10,860
  • 4
  • 43
  • 64