Schedule appointments with Rails 3 and jQuery

February 21, 2012 § Leave a comment

Problem: I needed a dynamic appointment scheduler that will instantly run a date chosen by a user against all the available time slots for that date. The scheduler then needs to dynamically hide the time slots that have already been chosen.

Solution: jQuery’s datepicker plugin and .ajax() function.

I’ll demonstrate this in an MVC context. All code can be had on Github.


First, we need to create an appointment model. So in the terminal run:

rails generate model Appointment date:string hour:string

We use a string datatype for ‘date’ because we’ll want to present the ‘yy-mm-dd’ formatted date immediately to the user. Setting hour:string allows the records to have leading zeros which allows us to set four digits for any hour e.g. 1300 and 0900 which in turn makes string pattern matching easier. We’ll use military time to help facilitate this as well.

Now, for our appointment class:


class Appointment < ActiveRecord::Base
attr_accessible :date, :hour

validates :date,  :presence => true
validates :hour,  :presence => true,
                  :uniqueness => {:scope => :date}

Here, we ensure that no model is persisted unless its date and hour properties are set. We also declare a qualifier for the hour’s uniqueness key – forcing any duplicate hours under the same date to be rejected. This server-side filter is critical for cases when two users both clear the client-side JavaScript protection at the same time. If both attempt to submit the exact same hour and date, Active Record will prevent the more recent submission from persisting.

In the view, we load the necessary jQuery-ui css file at the top, followed by the calendar, hour_picker and appointment_form divs. These divs will switch their hidden/shown status throughout the scheduling workflow. JS files required by jQuery as well as our custom appointment.js file round out our view template. Here is the entire view template for reference.

The controller contains our three needed RESTful routes. If you are confused about REST and how it relates to Rails, read this first followed by this. Our controller:

class AppointmentsController < ApplicationController

  def index
    date_from_ajax = params[:matched_date]
    reduce = Appointment.where(:date => date_from_ajax)
    hour_on_date = reduce.collect {|x| x.hour}
    @new_dates = hour_on_date
    render :layout => false

  def new
    @appointments = Appointment.create
      respond_to do |format|

  def create
     @appointment = Appointment.create(params[:appointments])
        redirect_to new_appointment_path
        err = ''
        @appointment.errors.full_messages.each do |m|
        err << m
        redirect_to new_appointment_path, :flash => { :alert => "#{err}, please try again" }

Here, our ‘new’ route allows us to use ‘new_appointment_path’ in our views. The ‘index’ action, as we’ll see, allows us to match chosen dates to available hours. The ‘create’ action persists the data and I added some error handling as well.

For our routes, we need only add the following:

resources :appointments

Here, no appointment-specific routes need to be hardcoded – a distinct advantage of RESTful architecture.


Upon visiting ‘/appointments/new’, a user sees nothing but the interactive jQuery calendar because we’ve hidden the ‘hour_picker’ and ‘appointment_form’ divs using jQuery’s .hide() function which is triggered upon page load. Another anonymous, document.ready function calls the .datepicker() function rendering the calendar. Clicking a datebox in the calendar itself triggers the ‘onSelect:’ callback function:

$(function () {
    var currentTime = new Date()
    var month = currentTime.getMonth()
    var day = currentTime.getDate()
    var year = currentTime.getFullYear()

        minDate: new Date(year, month, day),
        dateFormat: 'yy-mm-dd',
        onSelect: function(dateText) {
          $("th.selected_date").append("Date Chosen:" + " " + (dateText));
          pageNo = '2';

The ‘onSelect:’ function reverses the user interface by hiding the calendar and showing the hour_picker div. ‘dateText’ is the date value chosen by our user – we pass this value to our ‘findHours’ function which does nothing for now because no dates have ever been chosen. We’ll revisit this when we try to save the same date twice.

The unveiled hour_picker div offers the user a list of standard business-day hours.

<div id='hour_picker'>
<table border="1">
<th class = 'selected_date'></th>
<tr class = 'cal_table'>
<td type ="button" onclick = "nextPage('0700'," class = '0700' id = "7:00 am">7:00 am</td>
<tr class = "cal_table2">
<td type ="button" onclick = "nextPage('0800'," class = '0800' id = "8:00 am">8:00 am</td>
<tr class = "cal_table">
<td type ="button" onclick = "nextPage('0900'," class = '0900' id = "9:00 am">9:00 am</td>
<tr class = "cal_table" id = '5'>
<td type ="button" onclick = "nextPage('1100'," class = '1100' id = "11:00 am">11:00 am</td>
<tr class = "cal_table2" id = '6'>
<td type ="button" onclick = "nextPage('1200'," class = '1200' id = "12:00 pm">12:00 pm</td>
<tr class = "cal_table" id = '7'>
<td type ="button" onclick = "nextPage('1300'," class = '1300' id = "1:00 pm">1:00 pm</td>

Here, each table row is a button which triggers the ‘nextPage’ function (seen below) with two parameters – the button’s id and a string that is a duplicate of the button’s class. Matching the button’s class to a ‘nextPage’ parameter will allow us to block, hide, or disable one or more of these buttons in the future in order to prevent duplication.

 function nextPage(hour, id){
        document.getElementById('appointments_date').value = setFinalDate;
        document.getElementById('appointments_hour').value = hour;
        document.getElementById('subData').style.display = 'block'
        $('#final_date h2').append(setFinalDate);
        $('#final_hour h2').append(id);
        pageNo = '3';
        return true;

Here, we continue our liberal use of jQuery’s .hide() and .show() methods. We also set input values to the user-chosen date and the user-chosen hour respectively.

Finally the user sees the form to submit. The values have been added to hidden fields to prevent the user from changing them at this point in the process. Instead, to allow the user to review their selections before submission, we use jQuery’s .append() to peg the chosen date and hour to specific divs.


So now a different use wants to book that exact same date and time. They hit a calendar date, say February 21, 2012, and, along with moving the user to the next phase, the onclick triggers the ‘findHours()’ function which is no longer useless:

function findHours(chosen_date){
      url: "/../appointments",
      cache: false,
      data: {matched_date:chosen_date},
      success: function(html){
        var hours_array = [];
        var hours_string = $("#hidden_hour_div").html()
        var one = hours_string.substring(2, 6);
        var two = hours_string.substring(10, 14);
        var three = hours_string.substring(18, 22);
        var four = hours_string.substring(26, 30);
        var five = hours_string.substring(34, 38);
        var six = hours_string.substring(42, 46);

        for (var j in hours_array) {
          (final_array = '\.'+ hours_array[j]);

This function dynamically checks the user-chosen date for any of its hours that may have already been booked. We pass the chosen_date to jQuery’s wonderful .ajax() function which creates a GET request by attaching the chosen_date value to the URI string. We set the ‘cache’ property to false causing a current timestamp to automatically be attached to the URI – we don’t use the timestamp here but you might have a use for it later. Also, we don’t want to cache the data should the user revisit the scheduler in the same session.

.ajax() is a higher-order function, meaning that if certain conditions are met, it returns a ‘success’ callback function. This callback takes the hours of our user-chosen-date – returned as a comma-delimited sting to the index view (more on this later) – and converts the hours into the elements of a new array by using javascript string manipulation techniques.

By sending a GET request to /../appointments, we call the index method in our appointments_controller. This method…

  def index
    date_from_ajax = params[:matched_date]
    reduce_date = Appointment.where(:date => date_from_ajax)
    hour_on_date = reduce_date.collect {|x| x.hour}
    @new_dates = hour_on_date
    render :layout => false

takes the GET request’s matched_date value and queries the database with it. We then reduce the date to a collection of hours and make the result viewable with the instance variable @new_dates. Finally, since we’ll be passing this html back to our new.html.erb view, we need to disable the Rails layout lest we send a huge string of unnecessary html wrapping the html that we want.

Speaking of new.html.erb, you’ll notice this snippet..

<div id = "hidden_hour_div"></div> where we’ll peg the string returned from our index method. The second part of the findHours() function manipulates this string into an array. We then cycle through the array, attaching a ‘.’ in front of each element so that jQuery can recognize each element as a particular class in our view and hide those classes accordingly. Why do we add the ‘.’ after the fact? Because ID and class tokens must begin with a hexadecimal ([0-9A-Za-z]) so we can’t call our

classes ‘.0900’ for instance.

An alternate strategy for findHours() is to have the data converted to JSON in the controller and then parsed with jQuery.parseJSON() in appointment.js. But this would require increased steps in both the Rails initialization directory, and in your Appointment’s model.

So we’ve covered the scheduler’s main components as well as the workflow for creating a new date/hour record and the process of preventing the duplication of a date/hour record.

I packaged this code as a Ruby Gem but running the generator only provides a scaffold for you to build a more robust scheduling feature.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

What’s this?

You are currently reading Schedule appointments with Rails 3 and jQuery at seminal.


%d bloggers like this: