The datetime_select and time_select helpers are used to generate a block of dropdown fields for choosing the date and time (or only time) inside the form. By default, minutes are displayed from 00 to 59 in increments of 1.
Often this accuracy is not needed, and in addition, it is inconvenient to use a drop-down list of 60 values. The parameter: minute_step allows you to specify the necessary step for changing the value of minutes.
Like so much in Rails, these helpers have some level of “intelligence” —for the value of “default” they use the current date and time (unless you specify: include_blank => true). And with this there is a small problem. About her and her decision read below.
')
What is the problem?
It is that when using the: minute_step option, the minute value is rounded to 00, if the time value passed to the helper is not a multiple of the value: minute_step. Thus, specifying: minute_step => 5 we will get the effect of inability to display 42 minutes.
It is clear that if your application “counts” the minutes with a certain step, then the values ​​of the minutes will also be multiples of this step. But what to do when creating a record? Those. when the current time is set, and this is not always a multiple step.
Suppose we have a step of 5 minutes, and the current time is 15:42, then in the form of creating a record you will see a time of 15:00, and you will need to click and choose the nearest convenient value (40 or 45 minutes). This is not always convenient.
Solution option?
One option is to round the value of the current time to a multiple of our step. In the code, it will appear like this:
<%= datetime_select :created_at, :default => (Time.current.min % 5).minutes.ago(Time.current), :minute_step => 5 %>
or for time_select
<%= time_select :created_at, :default => (Time.current.min % 5).minutes.ago(Time.current), :minute_step => 5 %>
Thus, we will always have in the input fields of minutes the nearest to the convenient for us value.
Have a nice work!
From
the Hash Train blog