AddThis

Monday, October 31, 2016

Migrating in Phoenix

Phoenix Migration

This is part of the series on Phoenix, taking you from noob to !noob. Here are the list of posts so far:
  1. Intro
  2. Scaffolding

Today we will look at the migration file that's produced from the scaffolding we performed last time.

Migration File


defmodule PhoenixLibrary.Repo.Migrations.CreateBook do
  use Ecto.Migration

  def change do
    create table(:books) do
      add :title, :string
      add :author, :string
      add :description, :text

      timestamps()
    end

  end
end

At the end of generating the scaffold, we created the file above - priv/repo/migrations/20161014160805_create_book.exs. We are going to take a quick look at it and figure out what it's doing.

In the Rails world, we would have gotten a file like this:


class CreateBooks < ActiveRecord::Migration[5.0]
  def change
    create_table :books do |t|
      t.string :title
      t.string :author
      t.text :description

      t.timestamps
    end
  end
end

What's great is that the same basic thing that we are doing in Rails we are doing in Phoenix. In the Rails version we are creating a class to capture us creating a new books table and in the Phoenix version, we aren't creating a class, but instead creating a module.

In the Rails world, we are extending from ActiveRecord, but in Phoenix we are using helpers from Ecto.Migration. The important method that we are defining is the `change` method. This allows us to go forwards or backwards in our migration, to either create or tear down the table.


# Rails is rake db:migrate
mix ecto.migrate         # Runs migrations up on a repo

# Rails is rake db:rollback
mix ecto.rollback        # Reverts migrations down on a repo

The change method in both worlds take two arguments, a symbol representing the table we are going to create and a block where we create the actual columns in the table. In Rails we get a helper object that we can use to call functions where as in Phoenix we don't have/need a helper and can just call the add function passing in the name of the column and the type. And of course in Phoenix we call the timestamps function to create the created_at and updated_at column. But, in Rails we call the timestamps method on the helper.

In the future, we will dig into the models that are created from the scaffold command.

1 comment:

i Digital Academy said...

Thanks for sharing the information...
SEO Training in Bangalore | SEO Course Fees | Best SEO Classes - Join SEO Training in Bangalore at i Digital Academy and learn how to increase your website Traffic by
Google Certified Trainers with 100% Placements and affordable course fees. Book a Free Demo!