Rails Tip No.1: Making datetime_select more appointment-friendly

This is the first of what I intend to have as an ongoing list of Ruby on Rails programming tips. These are as much for plugging my own memory holes as they are for the general Googlejuice. Each should be a brief illustration of some technique on how to accomplish something in Ruby on Rails – probably in the form of a short code snippet with explanation. I should preface this all by stating that I am by no means an expert on Rails – I’ve been using it since late 2007 – so any urge to expound upon these thoughts by the Lightning Rails Ninjas™ out there would be most welcome indeed. Please feel free to comment.

The first one I’d like to present is how to get the datetime_select helper method to be slightly more user-friendly for your garden-variety appointment form.

Consider you have a form set up already for booking appointments. You may have used datetime_select for the start and end times for your form. The default implementation gives you the current date and time as defaults, and each item is rendered as a select menu.

But rarely would you want to do a new appointment on the same day and at at 12:06 PM, right? More often those things are scheduled at least a day in advance, and on the :00, :15, :30, and :45 minute marks. Or at the very least, having five minute increments for the minute menu should help pare down the options and make things simpler. Here’s an example of how something like this could be accomplished:

For the above example, we have a datetime_select form helper for the appointment_start column in our database. Simple enough – this is probably how a default code snippet would look from say a scaffold generation. Following that, we’ve passed a couple of extra bits of information to our helper – a default date and time, and a specification on how we should increment the minutes column.

:default => 24.hours.from_now does exactly what you’d expect – sets the default date and time for all the menus ahead one day. You could just as easily say three days from now, four years from now, and so on. And :minute_step => 5 gives us the five minute increments that we want. Set it to 15 if you’d like to pin it down to the :00, :15, :30, and :45 minute marks. Simple!

Leave a Reply

Your email address will not be published. Required fields are marked *