Evanto
Evanto

Reputation: 350

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

In Rails 5.1 I have a dropdown created with time_select helper from a table column of "time" data type:

<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>

The prompt sets the dropdown to "Hours" string by default. In html, this line doesn't have any value:

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

However, when a user doesn't choose anything from the dropdown and submits it with the default "Hours" option, the form sends the value to the db:

0001-01-01 00:00:00

Since the value of "Hours" isn't nil, my validation (which should give user a notice if nothing was selected from the dropdown) doesn't work.

How can I still have "Hours" default but set this option's value to nil (prohibit sending any values to the db on submission of this option) and be able to give user a notice like "Choose an hour!" in this case?

Upvotes: 1

Views: 42

Answers (1)

Evanto
Evanto

Reputation: 350

It turned out that all you needed to have a default prompt that sends null to db if no option is selected and sends value to db if an option is selected is to add ignore_date: true to f.time_select attributes. So I just turned

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

to:

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

Upvotes: 1

Related Questions