Skip to content

Instantly share code, notes, and snippets.

@davidrf
Last active August 29, 2015 14:23
Show Gist options
  • Save davidrf/97da72b6fe4efae164d4 to your computer and use it in GitHub Desktop.
Save davidrf/97da72b6fe4efae164d4 to your computer and use it in GitHub Desktop.
More exercises for AR associations
For this exercise, you're going to draw the ER diagram for a dog only veterinary website. You will not write any code. You will need a pencil and paper. Each table should be drawn as a square and it should have the title of the table, the column names of foreign keys if there are any, and the Active Record association it needs if any. Don't go overboard with adding additional columns, for example in a real app having a users address, state, city, telephone, and other contact information might be good to have, but for this exercise a first and last name column would suffice.
Keep in mind some basic concepts:
* If table A has a foreign key, it will need a belongs to association. i.e. a video game table will have a foreign id that is 'gamer_id' and it will need a 'belongs_to :gamer' association.
* Associations come in pairs, objects in table A belong to objects in Table B, then Table B needs to have a has_one/has_many association. i.e. a video game belongs to a person, and a person has many video games
* Association pairs are usually inverses of each other (i.e. belongs_to is the inverse of has_one/has_many). This rule is not true when you have two objects that have many of each other (i.e. a movie has many actors and an actor has many movies)
* For has_many through relationships, you need a join table, and you need a has many with the join table first. i.e For tables: movies, cast_members, and actors. An actor has many cast members and an actor has many movies through cast members.
1. Let's first start by drawing the tables and relationships between a dog and a dog owner. Ask yourself, can a dog owner have many dogs? Can a dog have many dog owners? How many tables do I need?
2. I want to have a vaccine card object for each dog. Draw the appropriate tables and relationships.
3. Let's start modeling our veterinary business. We have a couple of veterinary buildings, and we want to have an appointment schedule for each dog. Our appointment schedule should let us know where the appointment is, what dog has the appointment, what ownder has the appointment, and what time the appoitnment is. Draw the appropriate tables and relationships.
4. We also have veterinary physicians, let's keep track of what doctor is at each appointment. I also want to know what dogs the doctor is taken care of, and owners also want to know what doctors their dogs have had.
5. Finally we want to know if any dogs are boyfriend/girlfriend with each other. Draw the appropriate tables and relationships.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment