如何禁止下拉列表的特定选项发送值?

How to Prohibit a Particular Option of a Dropdown to Send Value?

在 Rails 5.1 中,我使用来自 "time" 数据类型的 table 列的 time_select 助手创建了一个下拉列表:

<div class="col-md-12">
   <%= form_for(Sleep.new) do |f| %>
   <%= f.time_select :hours, {minute_step: 5, prompt: true, order: [:hour]} %>
   <%= f.submit "Submit" %>
   <% end %>
</div>

默认情况下,提示将下拉列表设置为 "Hours" 字符串。在 html 中,此行没有任何值:

<select id="sleep_hours_4i" name="sleep[hours(4i)]">
<option value="">Hour</option>
<option value="00">00</option>

但是,当用户未从下拉列表中选择任何内容并使用默认 "Hours" 选项提交时,表单会将值发送到数据库:

0001-01-01 00:00:00

由于 "Hours" 的值不为零,我的验证(如果未从下拉列表中选择任何内容,应向用户发出通知)不起作用。

我怎样才能仍然拥有 "Hours" 默认值,但将此选项的值设置为 nil(禁止在提交此选项时向数据库发送任何值)并能够向用户发出通知,例如 "Choose an hour!" 在这种情况下?

事实证明,如果没有选择任何选项,将 null 发送到 db,如果选择了一个选项,则将值发送到 db,你只需要有一个默认提示,就是将 ignore_date: true 添加到 f.time_select 属性。所以我刚转

<%= f.time_select :hours, {minute_step: 5, prompt: true, order: [:hour]} %>

至:

<%= f.time_select :hours, {minute_step: 5, prompt: true, ignore_date: true, order: [:hour]} %>