Defining the User Schema and Migration

At its core, Ecto lets you specify a struct that ties individual fields to the fields in database tables through a DSL. Let’s use that now. To define our schema, let’s replace our bare user struct in lib/rumbl/accounts/user.ex with the following:

 defmodule​ Rumbl.Accounts.User ​do
 use​ Ecto.Schema
 import​ Ecto.Changeset
 
  schema ​"​​users"​ ​do
  field ​:name​, ​:string
  field ​:username​, ​:string
 
  timestamps()
 end
 end

This DSL is built with Elixir macros. The schema and field macros let us specify both the underlying database table and the Elixir struct at the same time. Each field corresponds to both a field in the database ...

Get Programming Phoenix 1.4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.