Question: How do I split datetime into two separate form fields?
I have the following:
<%= f.label :Borrowed, "Check Out Date*" %></td>
<%= f.date_field :Borrowed, :id => "datepicker", min:Date.today, :ignore_time => true, :required => true %></td>
<%= f.label :Borrowed, "Check Out Time*" %>
<%= f.time_field :Borrowed, min:"9:00 AM", max: "4:30 PM", default:"10:00 AM", :ignore_date => true, :required => true%>
<td><%= f.label :Returned, "Check In Date" %>
<td><%= f.date_field :Returned, :id => "datepicker", min:Date.today, :ignore_time => true, :required => true %>
<td><%= f.label :Returned, "Check In Time*" %>
<td><%= f.time_field :Returned, min:"9:00 AM", max: "4:30 PM", default:"10:00 AM", :ignore_date => true, :required => true%>
I have two datetime fields in my database: Borrowed and Returned. I wanted to split up the date and the time so the user could pick a date from a calendar using a jQuery script. (This may be the problem...) What happens is when I fill out and submit the form the time saves correctly, but the date is the same on both Borrowed and Returned.
In the database it looks like this:
Returned: 2016-12-09 15:00:00 -0800
Borrowed: 2016-12-09 10:00:00 -0800
jQuery
$('#datepicker').datepicker({format: 'dd/mm/yyyy'});
Gems
gem 'bootstrap-timepicker-rails'
gem 'bootstrap-datepicker-rails'
You can't have two fields with the same name like:
<%= f.date_field :Borrowed, :id => "datepicker", min:Date.today, :ignore_time => true, :required => true %></td>
<%= f.time_field :Borrowed, min:"9:00 AM", max: "4:30 PM", default:"10:00 AM", :ignore_date => true, :required => true%>
Doing so will definitely give you the value for one field, and the value for the field with the same name will be overridden.
What you would like to can be accomplished using the following two ways:
You may have two columns in your table to store two values: date, and time. Rails provides the following two datatypes to store things date and time.
add_column :table_name, :borrowed_date, :date # It will store day, month & year.
add_column :table_name, :borrowed_time, :time # It will store hours, minutes & seconds.
date_field_tag
& time_field_tag
Instead of relying upon form_for
to generate the values for us, in this scenario, you will have to take responsibility.
<%= date_field_tag :borrowed_d # other options %>
<%= time_field_tag :borrowed_t # other options %>
Now, Rails won't complain regarding the existence of columns: borrowed_d
& borrowed_t
, and at the same, it won't save the values for these columns either. So in your controller, now you manually need to take the values for borrowed_d
, and borrowed_t
, combine them into one, and save that thing against borrowed
in the database.
Not only that, in case of editing an ActiveRecord
object, you will have to gather the two values from borrowed
, and show them in the form.