Search code examples
ruby-on-railsdatetimedatepickerruby-on-rails-4timepicker

Rails 4 - Convert datetime into separate date and time fields


How can you convert a mysql datetime field into two form fields (1) date only, (2) time only, and combine both fields back into datetime format on form submit?

This would allow the use of the following gems, but store the dates in a single datetime field:

gem 'bootstrap-datepicker-rails'
gem 'bootstrap-timepicker-rails'

Thanks in advance!


Solution

  • Found the solution with help from @Althaf

    Added virtual attributes to model.rb Used before_save callback to convert back to datetime.

    before_save :convert_to_datetime
    
    def sched_date_field
      sched_date.strftime("%d/%m/%Y") if sched_date.present?
    end 
    
    def sched_time_field
      sched_time.strftime("%I:%M%p") if sched_time.present?
    end
    
    def sched_date_field=(date)
      # Change back to datetime friendly format
      @sched_date_field = Date.parse(date).strftime("%Y-%m-%d")
    end
    
    def sched_time_field=(time)
      # Change back to datetime friendly format
      @sched_time_field = Time.parse(time).strftime("%H:%M:%S")
    end
    
    def convert_to_datetime
      self.sched_time = DateTime.parse("#{@sched_date_field} #{@sched_time_field}")
    end
    

    Using Rails 4, needed to add sched_date_field and sched_time_field to strong params in controller.rb

    Here are the fields in _form.html.erb

    <%= f.label :sched_date_field, "Scheduled Date" %>
    <%= f.text_field :sched_date_field, :class => "datepicker" %>
    
    <%= f.label :sched_time_field, "Scheduled Time" %>
    <%= f.text_field :sched_time_field, :class => "timepicker" %>