Ruby on Rails: time_select default value

RichiMartin picture RichiMartin · Aug 26, 2014 · Viewed 7.4k times · Source

I have been looking for a solution for this problem for hours. There are plenty of recommendations even here on stackoverflow and I tried all of them but none of them work in my case and I don't know why.

I have the current version of RoR [4.1.5] running on my server and I have a form in which the user has to select a "time from" and a "time to" value.

<p>
<%= f.label :Time %><br>
<%= f.time_select :timefrom, {minute_step: 60} %> to <%= f.time_select :timeto, {minute_step: 60} %>
</p>

I get the default values from the database. In order to fetch them, I just collect the last time value which has been entered. Which usually is a timeframe of 1 hour:

<% changetimeto = (Production.select("timeto").last.timeto).strftime("%H:%M")   %>
<% changetimefrom = (Production.select("timeto").last.timeto + 3600).strftime("%H:%M")  %>

So I tried:

<%= f.time_select :timefrom, {minute_step: 60}, :selected => changetimeto %> to <%= f.time_select :timeto, {minute_step: 60}, :selected => changetimefrom %>

or :value => or :default =>

but nothing seems to work, it doesn't even give me an error. I checked the variables in changetimeto and changetimefor and they have the right value, its like "14:00" and "15:00". But as I said, it doesn't do anything.

I also tried to address hours and minutes separately with :default => {hours: '14', minutes: '00'}, etc. but that also doesn't work, not even causing an error. Just nothing. It still defaults to the actual time.

Does anyone have a recommendation or hint for me?

Answer

Vardarac picture Vardarac · Aug 26, 2014

Defaults in time_select (for those who've not been following the comment thread) work like this:

<%= time_select :name, 'method', {options}, {:default => {:hour => '10', :minute => '30'}} %>

If we want the time select to default to 10:30.