Separate date and time form fields in Rails

后端 未结 5 674
轮回少年
轮回少年 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:15

    Do you have to have a text_field in the view?

    As far as I can tell, you can have a date_time field and then just use two different input fields to set the different parts of the field.

    form_for @event do |f|
      f.date_select :starts_at
      f.time_select :starts_at, :ignore_date => true
      f.submit
    end
    

    Since the rails date and time select helpers set five different parameters (starts_at(1i) for the year part, 2i for the month part, and so on), that means that the date_select only sets them for the date part, while if you pass :ignore_date => true to the time_select, it will only set the hour and minute part.

    If you must have a text_field I'm not sure how to do it, but it might be possible to do using some jQuery magic before setting the datetime parameters before sending the form.

提交回复
热议问题