Separate date and time form fields in Rails

后端 未结 5 681
轮回少年
轮回少年 2020-12-23 16:43

I have an ActiveRecord model Eventwith a datetime column starts_at. I would like to present a form, where date and time for starts_at

5条回答
  •  一向
    一向 (楼主)
    2020-12-23 17:03

    Elegant solution may provide date_time_attribute gem:

    class MyModel < ActiveRecord::Base
      include DateTimeAttribute
    
      date_time_attribute :starts_at
    end
    

    It will allow you to set starts_at_date and starts_at_time separately:

    form_for @event do |f|
      f.text_field :starts_at_date
      f.text_field :starts_at_time
      f.submit
    end
    
    # this will work too:
    form_for @event do |f|
      f.date_select :starts_at_date
      f.time_select :starts_at_time, :ignore_date => true
      f.text_field  :starts_at_time_zone
      f.submit
    end
    
    # or
    form_for @event do |f|
      f.date_select :starts_at_date
      f.text_field  :starts_at_time
      f.submit
    end
    

    It will also allow you to play with time zones, use Chronic etc.

提交回复
热议问题