mix phx.gen.schema (Phoenix v1.5.7) View Source

Generates an Ecto schema and migration.

mix phx.gen.schema Blog.Post blog_posts title:string views:integer

The first argument is the schema module followed by its plural name (used as the table name).

The generated schema above will contain:

  • a schema file in lib/my_app/blog/post.ex, with a blog_posts table
  • a migration file for the repository

The generated migration can be skipped with --no-migration.


Your schemas can be generated and added to a separate OTP app. Make sure your configuration is properly setup or manually specify the context app with the --context-app option with the CLI.

# Via config
config :marketing_web, :generators, context_app: :marketing

# Via CLI
mix phx.gen.schema Blog.Post blog_posts title:string views:integer --context-app marketing


The resource fields are given using name:type syntax where type are the types supported by Ecto. Omitting the type makes it default to :string:

mix phx.gen.schema Blog.Post blog_posts title views:integer

The following types are supported:

  • :integer

  • :float

  • :decimal

  • :boolean

  • :map

  • :string

  • :array

  • :references

  • :text

  • :date

  • :time

  • :time_usec

  • :naive_datetime

  • :naive_datetime_usec

  • :utc_datetime

  • :utc_datetime_usec

  • :uuid

  • :binary

  • :datetime - An alias for :naive_datetime

The generator also supports references, which we will properly associate the given column to the primary key column of the referenced table:

mix phx.gen.schema Blog.Post blog_posts title user_id:references:users

This will result in a migration with an :integer column of :user_id and create an index.

Furthermore an array type can also be given if it is supported by your database, although it requires the type of the underlying array element to be given too:

mix phx.gen.schema Blog.Post blog_posts tags:array:string

Unique columns can be automatically generated by using:

mix phx.gen.schema Blog.Post blog_posts title:unique unique_int:integer:unique

If no data type is given, it defaults to a string.


By default, the table name for the migration and schema will be the plural name provided for the resource. To customize this value, a --table option may be provided. For example:

mix phx.gen.schema Blog.Post posts --table cms_posts


Generated migration can use binary_id for schema's primary key and its references with option --binary-id.

Default options

This generator uses default options provided in the :generators configuration of your application. These are the defaults:

config :your_app, :generators,
  migration: true,
  binary_id: false,
  sample_binary_id: "11111111-1111-1111-1111-111111111111"

You can override those options per invocation by providing corresponding switches, e.g. --no-binary-id to use normal ids despite the default configuration or --migration to force generation of the migration.