Understanding the role of schemas
The first thing to start understanding is where and how schemas define the shape of the data in your database. Schemas help describe what tables your application uses behind the scenes and what fields exist to Ecto; the Schemas themselves do not define the overall structure to the database itself.
This helps describe the columns and define what types each of the columns are (for example, a string, an integer, or a reference to another table). The important thing to note about schemas in Ecto is what they are intended to do: separate the ideas of data from operations. By keeping our schemas very specific to understanding, describing, and translating the data, we can keep our applications largely side-effect-free when interacting with the database!
Before we can take a really deep dive into schemas, we should start by talking about what our initial voting data model should look like! Let's take a look at the code we introduced for our data model in the controller that we wrote in the last chapter:
poll = %{
title: "My First Poll",
options: [
{"Option 1", 0},
{"Option 2", 5},
{"Option 3", 1}
]
}
Based on this, we can probably decide that our model for our Vote concept in the database can be a pretty simple thing. We have the Vote itself, which has a title attached to it, and then the options that people can decide between. We're going to make an assumption here that you're using the default database choice for Phoenix applications, Postgres (but it shouldn't change much regardless of your database choice!). So, a very simple database table model would be:
Poll | Title Options (reference to another table |
Option | Poll ID (reference to the poll this option is attached to) Title Votes |
This creates two separate tables: Polls and Options. The Polls table will store all of the Polls themselves and then the options table will store the possible vote choices and their current scores. The Options table will store a reference back to the original poll (we'll get into this later when we start talking about associations). This is typically referred to as a "one to many" relationship between the two tables; a Poll can have many Options, but an Option can only have one Poll. This also means that the referencing of different tables only needs to take place on the Option, not on the Poll.