6

I'm trying to make a time field in my form optional. I'm doing this:

<%= f.time_select :end_time, minute_step: 5, include_blank: true %>

However when it is submitted, since there is default date information being submitted automatically with time_select, this is what the params looks like:

end_time(1i): '2000' end_time(2i): '1' end_time(3i): '1' end_time(4i): '' end_time(5i): ''

Rails interprets this as a real date and sets end_time to 00:00

Is there any fix/workout to be able to have an optional time field? I tried this in the controller:

if params[:event][:end_time] && params[:event][:end_time][:hour].blank? && params[:event][:end_time][:minute].blank?
  params[:event][:end_time] = nil
end

But it doesn't seem to work.

Any help is appreciated!

ryanio
  • 63
  • 3

2 Answers2

6

Following along the same lines, something that worked well for me was this:

Add a before filter/action to the controller

before_filter :filter_blank_end_time, only: [:create, :update]

Create the filter

def filter_blank_end_time
    if params[:event]['end_time(4i)'].blank?
        params[:event]['end_time(1i)'] = ""
        params[:event]['end_time(2i)'] = ""
        params[:event]['end_time(3i)'] = ""
        params[:event]['end_time(4i)'] = ""
        params[:event]['end_time(5i)'] = ""
    end
end

Passing in empty stings for all fields seem to yield a NIL value for end time.

caseyli
  • 479
  • 5
  • 9
  • 1
    I had a similar problem when submitting blank/nil time. Your above solution works but I had to check `blank?` on `(5i)` as that's how my time field was being stored, not in the `(4i)` params. Thanks for the tip! – nulltek Sep 28 '14 at 13:10
2

Your param is not [:event][:end_time], they are:

[:event]['end_time(1i)']..[:event]['end_time(5i)'] respectively.

Making the param value nil won't help, you need to reject that key from your params hash; e.g.

params[:event].except('end_time(4i)', 'end_time(5i)') if params[:event]['end_time(4i)'].blank?

  • Thanks! Almost there. If I .except the end_time, then it won't update the record to blank values if it already had a time value in it. Any way to set it to nil somehow instead? – ryanio Jun 01 '12 at 14:17
  • Nevermind, got it. Thanks again! Loading the attributes, then doing before the save: @event.end_time = nil if params[:event]['end_time(4i)'].blank? – ryanio Jun 01 '12 at 14:29