Phoenix v1.3.4 mix phoenix.gen.model View Source

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 schema file 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. Omitting 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 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 schema’s primary key and its 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 the following to your model function in web/web.ex or 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. 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.