I have a friend who is in need of a scheduling app. I would like to use this opportunity to create a web app that can help him with his nascent business. Since I have been learning Ruby on Rails for the past 10 weeks, that is the framework I will be using to design the models and set up the relationships.

First, we have to come up with the models. What do we need for this simple web app? There will be a User, with many Appointments, and each Appointment will belong to a User. There will also have to be a class to model Appointment Slots. They will keep track of all the Appointment Slots for Appointments, and the id of the Appointment scheduled for that slot. If no Appointment is scheduled for the Appointment Slot, the Appointment id will be nil.

The Entity-Relationship Diagram

Hopefully, it is clear why Users would have many Appointments. But you might be wondering why Appointments would not have any date or time fields. This is because it is only a join table to link the actual Appointment Slots with the User. You can think of it like this: A client(User) will be able to make many appointments, but if we want to know when that appointment is, we will have to ask the database to look up the id of the Appointment Slot, where the date/time will be stored.

This idea of a join table is kind of strange when you first encounter it, but it makes sense when you think realize that in object modeling, you only want to store the most essential attributes of your model to avoid duplicating elements across tables. If you have the same information in two tables, you have to update it in two places, and it can get out of sync. We do not want to keep any dates or time in our model Appointments, because we want to track that data in one table and in one table only: the Appointment Slot table.

Let’s start by making the models and creating the database. I will assume that you have Rails and Ruby installed on your computer. From the command line, type:

rails new scheduler -d postgresql
cd scheduler
rake create:db
rails g model User name:string email:string phone_number:string
rails g model Appointment user_id:integer
rails g model AppointmentSlot start_time:datetime length:integer appointment_id:integer

rake db:migrate

Go into your new app/models and type:

class User < ActiveRecord::Base
  has_many :appointments
  has_many :appointment_slots, :through => :appointments
end

class Appointments < ActiveRecord::Base
  belongs_to :user
  has_many :appointment_slots
end

class AppointmentSlots < ActiveRecord::Base
  belongs_to :appointment
end

Now we have the basic object model and database to support the first iteration of our application. In my next posts, I will be covering user authentication and building CRUD functionality for all the models we have so far. After that, I will be iterating on this design to build more features.