Writing the migration file

If we look back to our planned design for the uploads table, we came up with the following criteria for what we figured we'd need: We'll need a table to store the URL or path, the poll ID, the user ID, the alt text, and a caption. Let's create our migration and do all of the work the hard way so that we can reinforce all of these concepts and continue to learn how to build an Elixir and Phoenix app at a deep level! We'll start by generating the migration and then editing that generated file:

$ mix ecto.gen.migration create_images_table
* creating priv/repo/migrations
* creating priv/repo/migrations/20171117232649_create_images_table.exs

Then, we open up the migration file:

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

def change do
create table(:images) do
add :url, :string
add :alt, :string
add :caption, :string
add :poll_id, references(:polls)
add :user_id, references(:users)

timestamps()
end
end
end

What we're adding here is a URL that will keep track of what the display URL should be for the user, some alt text to display should the image not load (and for accessibility reasons (such as to enable screen readers)), a caption to display with the image, and then, finally, references back to the poll that state what this image is associated with and the user that uploaded the image in the first place.

This is a good minimum amount of information that will enable us to allow the user to upload images associated with their polls, give them clever captions, and store all of that information in the database and display it later. There are a lot of other ways to handle user uploads—for example, you could use something like Amazon S3 and store the images that you upload into an S3 bucket, and then store that as the URL for the image.

The nice thing about this particular schema is that it easily allows for that sort of behavior since, at the end of the day, it is just storing a URL, some extra display information about the image, and some of the image's general metadata regarding its relation to the rest of the database structure. It'd be pretty easy to swap out a filesystem-based upload system with something like S3!

Our migration is complete, so let's give it a quick run and make sure everything is good before we start moving on to implementing the schema!

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

If we take a look at the table structure, we should also see all of the columns in place, as expected!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset