官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 汉寿县| 子洲县| 临清市| 通江县| 海宁市| 遵化市| 乐都县| 长寿区| 贞丰县| 鹤庆县| 光山县| 浙江省| 晋江市| 历史| 洛阳市| 东阿县| 民县| 门头沟区| 城固县| 日土县| 农安县| 襄樊市| 山西省| 岳西县| 英山县| 循化| 偏关县| 樟树市| 邮箱| 岑溪市| 清水河县| 平安县| 临海市| 分宜县| 通州区| 古浪县| 哈巴河县| 辽宁省| 顺平县| 东山县| 绍兴县|