Search code examples
ruby-on-railsruby-on-rails-3simple-formfields-for

Howto combine two fields in form to one field in model


I have a column start of type datetime and want to display this as a text-field (to add a datepicker) and a time_select. I tried this with different methods and one was to use fields_for/simple_fields_for.

<%= f.simple_fields_for :start do |start| %>
  <%= start.input :date, :as => :string, :input_html => { :class => 'datepicker'} %>
  <%= start.input :time, :as => :time, :minute_step => 5, :input_html => { :class => 'input-small'}  %>
<% end %>

How can i transform this two fields to my needed datetime column in model? Or is there a better way to display two fields in a form matching one field in database?


Solution

  • You'll have to parse the seperate params in the controller and combine them to make a datetime.

    I'd suggest making a model called StartTime to parse it

    ...app/models/start_time.rb

    class StartTime
      extend ActiveModel::Naming
    
      attr_accessor :date, :time
    
      def initialize(date, time)
        @date = date.is_a?(String) ? Date.parse(date) : date
        @time = time
      end
    
      def to_timestamp
        # parse @date and @time into Datetime
    
    end
    

    Chronic is a helpful gem for parsing dates/time from strings

    Hope this helps