Phoenix v1.3.0-rc.0 Mix.Tasks.Phx.Gen.Schema
Generates an Ecto schema and migration.
mix phx.gen.schema Blog.Post blog_posts title:string views:integer
The first argument is the module name followed by its plural name (used for the schema).
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
.
Attributes
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
:naive_datetime
:utc_datetime
:uuid
:binary
:datetime
- An alias for:naive_datetime
The generator also supports belongs_to
associations
via references:
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. It will also generate
the appropriate belongs_to
entry in the schema.
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.
table
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 exampe:
mix phx.gen.schema Blog.Post posts --table cms_posts
binary_id
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 the :phoenix
application. These are the defaults:
config :phoenix, :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.
Summary
Functions
A task needs to implement run
which receives
a list of command line args
Functions
A task needs to implement run
which receives
a list of command line args.
Callback implementation for Mix.Task.run/1
.