Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional time_select with allow_blank defaults to 00:00

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!

like image 829
ryanio Avatar asked Jun 01 '12 13:06

ryanio


2 Answers

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.

like image 57
caseyli Avatar answered Nov 11 '22 22:11

caseyli


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?

like image 2
Jon-Paul Lussier Avatar answered Nov 11 '22 22:11

Jon-Paul Lussier