Phoenix Web Development
上QQ阅读APP看书,第一时间看更新

Creating our Options table migration

Hooray! We've created our migrations, and run them successfully! Now, we have our representation of the first table in our models. We’ll continue on with creating another migration for our Options since our data model will be woefully incomplete without it! Let's begin:

$ mix ecto.gen.migration add_options_table
* creating priv/repo/migrations
* creating priv/repo/migrations/20171005185040_add_options_table.exs

If we open up the file, we’ll see the same skeleton we started within our last file. The new things we'll be using here are default values, and references as well! If you remember the design of our Options table, we have a title (which is a string), the votes (which is an integer counter of the number of votes (which we should start off at zero)), and the poll_id, which is a reference back to the polls table. And, of course, we'll want to add our timestamps for audit information! Let's take a look at the finished file:

defmodule Vocial.Repo.Migrations.AddOptionsTable do
use Ecto.Migration

def change do
create table("options") do
add :title, :string
add :votes, :integer, default: 0
add :poll_id, references(:polls)

timestamps()
end
end
end

If all went well when we run mix ecto.migrate we should expect to see no errors:

$ mix ecto.migrate
[info] == Running Vocial.Repo.Migrations.AddOptionsTable.change/0 forward
[info] create table options
[info] == Migrated in 0.0s

We've done it! We've created a database representation that matches our initial design and we can now start moving forward with the actual coding of our schemas! Let's take a look at the structure of this table that we've created to make sure what's in the database is what we're expecting to see overall:

One thing that we'll need to do is create a directory that will map all of the related concepts together (this is commonly referred to as a Context, but we're going to gloss over that for now). So, in our lib/vocial directory, we'll create a new directory called votes. Let's create our first schema in that directory: poll.ex.