Mix.Tasks.Phoenix.Gen.Model

Generates an Ecto model in your Phoenix application.

mix phoenix.gen.model User users name:string age:integer

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

The generated model will contain:

  • a model in web/models
  • 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. Ommitting the type makes it default to :string:

mix phoenix.gen.model User users name age:integer

The generator also supports belongs_to associations via references:

mix phoenix.gen.model Post 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 model’s 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 phoenix.gen.model User users nicknames:array:string

Unique columns can be automatically generated by using:

mix phoenix.gen.model Post posts title:unique unique_int:integer:unique

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

Namespaced resources

Resources can be namespaced, for such, it is just necessary to namespace the first argument of the generator:

mix phoenix.gen.model Admin.User users name:string age:integer

binary_id

Generated migration can use binary_id for model’s primary key and it’s references with option --binary-id.

This option assumes the project was generated with the --binary-id option, that sets up models to use binary_id by default. If that’s not the case you can still set all your models to use binary_id by default, by adding following to your model function in web/web.exoption or by adding following to the generated model before the schema declaration:

@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id

Default options

This generator uses default options provided in the :generators configuration of the :phoenix application. You can override those options 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

Callback implementation for c:Mix.Task.run/1

Functions

run(args)

Callback implementation for c:Mix.Task.run/1.