带有 allow_blank 的可选 time_select 默认为 00:00 [英] Optional time_select with allow_blank defaults to 00:00

查看:34
本文介绍了带有 allow_blank 的可选 time_select 默认为 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 %>

但是在提交的时候,由于time_select会自动提交默认的日期信息,所以params是这样的:

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'结束时间(2i):'1'结束时间(3i):'1'结束时间(4i):''end_time(5i): ''

Rails 将此解释为真实日期并将 end_time 设置为 00:00

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

但它似乎不起作用.

感谢任何帮助!

推荐答案

你的参数不是 [:event][:end_time],它们是:

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

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

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

使参数值为 nil 无济于事,您需要从 params 散列中拒绝该键;例如

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)') 如果 params[:event]['end_time(4i)'].blank?

这篇关于带有 allow_blank 的可选 time_select 默认为 00:00的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆