Rails time_select Form and View [Bonus: Date]

Luciana
3 min readAug 6, 2021

Wondering how can you work around the f.time_select form in Rails and how to property display inside the views? Here’s a practical tutorial.

My Rails project is a has many through relationship between: gyms, users, workouts and scores.

On my scores form, I wanted to display to users the minutes and seconds options only, no hours — this is how usually CrossFit scores workouts are set up.

Rails Form time_select

<%= f.time_select :result_time, :discard_hour => true, :default => {:minute => '00', :second => '00'}, :include_seconds => true %>

On this code above, it’s also to display as default 00:00 so that way the user can choose her/his workout time. Otherwise, the default time displayed is your current time.

Rails Form date_select

<%= f.date_select :date %>

I kept the default that shows up your current date.

Undefined Method for nil:NiClass

To display date and time on the view, I tried to use .strftime('%M:%S') for time and .to_s or .to_formatted_s(:long) for date. They worked at first, but they all end up with errors. These errors come when the data after the . (in this case, the date and time) is empty.

undefined method `strftime' for nil:NilClass

undefined method `to_formatted_s' for nil:NilClass

Handling Rails View Date and Time

To fix it, you’ll need to add 2 steps. First one, inside the Helper method include these codes:

These methods are handling in case the time or date are blank. If there are blank, it won’t display to the user otherwise will show up the value inside the format. In my case, I set up the time format to show up just the minutes and seconds '%M:%S' and for the date, I choose the :long format. Check the Ruby documentation to see more types of date formats or you can create your own.

2nd part, create a file inside config/initializers/date_time_formats.rb

Maybe your code will already work without this file inside the initializers. As you can see, my date was perfect working without it that why it’s commented out.

Inside the Views file Form, add these codes to display the date and time:

<%= format_date score.date %>
<%= format_time score.result_time, :time %>

The format_date is the Helper method being called and the :time is the method inside the Initializers folder. Try to add the :date in case your date is still not displaying correctly.

--

--