Ecto.Model.Schema

Defines a schema for a model.

A schema is a struct with associated metadata that is persisted to a repository. Every schema model is also a struct, that means that you work with models just like you would work with structs.

Example

defmodule User do
  use Ecto.Model.Schema

  schema "users" do
    field :name, :string
    field :age, :integer, default: 0
    has_many :posts, Post
  end
end

Types and casting

When defining the schema, types need to be given. Those types are specific to Ecto and must be one of:

Ecto type Elixir type Literal syntax in query
:integer integer 1, 2, 3
:float float 1.0, 2.0, 3.0
:boolean boolean true, false
:string UTF-8 encoded binary "hello"
:binary binary <<int, int, int, ...>>
:uuid 16 byte binary uuid(binary_or_string)
{:array, inner_type} list [value, value, value, ...]
:decimal Decimal
:datetime %Ecto.DateTime{}
:date %Ecto.Date{}
:time %Ecto.Time{}

Models can also have virtual fields by passing the virtual: true option. These fields are not persisted to the database and can optionally not be type checked by declaring type :any.

When manipulating the struct, it is the responsibility of the developer to ensure the fields are cast to the proper value. For example, you can create a weather struct with an invalid value for temp_lo:

iex> weather = %Weather{temp_lo: "0"}
iex> weather.temp_lo
"0"

However, if you attempt to persist the struct above, an error will be raised since Ecto validates the types when building the query.

Schema defaults

When using the block syntax, the created model uses the default of a primary key named :id, of type :integer. This can be customized by passing primary_key: false to schema:

schema "weather", primary_key: false do
  ...
end

Or by passing a tuple in the format {field, type, opts}:

schema "weather", primary_key: {:custom_field, :string, []} do
  ...
end

Implicit defaults can be specified via the @schema_defaults attribute. This is useful if you want to use a different default primary key through your entire application.

The supported options are:

Example

defmodule MyApp.Model do
  defmacro __using__(_) do
    quote do
      @schema_defaults primary_key: {:uuid, :string, []},
                       foreign_key_type: :string
      use Ecto.Model
    end
  end
end

defmodule MyApp.Post do
  use MyApp.Model
  schema "posts" do
    has_many :comments, MyApp.Comment
  end
end

defmodule MyApp.Comment do
  use MyApp.Model
  schema "comments" do
    belongs_to :post, MyApp.Comment
  end
end

Any models using MyApp.Model will get the:uuidfield, with type :string` as the primary key.

The belongs_to association on MyApp.Comment will also now require that :post_id be of :string type to reference the :uuid of a MyApp.Post model.

Reflection

Any schema module will generate the __schema__ function that can be used for runtime introspection of the schema.

Furthermore, both __struct__ and __assign__ functions are defined so structs and assignment functionalities are available.

Source

Summary

association(name, association, opts \\ [])

Defines an association

belongs_to(name, queryable, opts \\ [])

Indicates a one-to-one association with another model

field(name, type \\ :string, opts \\ [])

Defines a field on the model schema with given name and type

has_many(name, queryable, opts \\ [])

Indicates a one-to-many association with another model

has_one(name, queryable, opts \\ [])

Indicates a one-to-one association with another model

schema(source, opts \\ [], block)

Defines a schema with a source name and field definitions

Macros

association(name, association, opts \\ [])

Defines an association.

This macro is used by belongs_to/3, has_one/3 and has_many/3 to define associations. However, custom association mechanisms can be provided by developers and hooked in via this macro.

Read more about custom associations in Ecto.Associations.

Source
belongs_to(name, queryable, opts \\ [])

Indicates a one-to-one association with another model.

The current model belongs to zero or one records of the other model. The other model often has a has_one or a has_many field with the reverse association.

You should use belongs_to in the table that contains the foreign key. Imagine a company <-> manager relationship. If the company contains the manager_id in the underlying database table, we say the company belongs to manager.

In fact, when you invoke this macro, a field with the name of foreign key is automatically defined in the schema for you.

Options

  • :foreign_key - Sets the foreign key field name, defaults to the name of the association suffixed by _id. For example, belongs_to :company will have foreign key of :company_id

  • :references - Sets the key on the other model to be used for the association, defaults to: :id

  • :type - Sets the type of :foreign_key. Defaults to: :integer

Examples

defmodule Comment do
  schema "comments" do
    # This automatically defines a post_id field too
    belongs_to :post, Post
  end
end

# The post can come preloaded on the comment record
[comment] = Repo.all(from(c in Comment, where: c.id == 42, preload: :post))
comment.post #=> %Post{...}
Source
field(name, type \\ :string, opts \\ [])

Defines a field on the model schema with given name and type.

Options

  • :default - Sets the default value on the schema and the struct
  • :virtual - When true, the field is not persisted
  • :primary_key - When true, the field is set as primary key
Source
has_many(name, queryable, opts \\ [])

Indicates a one-to-many association with another model.

The current model has zero or more records of the other model. The other model often has a belongs_to field with the reverse association.

Options

  • :foreign_key - Sets the foreign key, this should map to a field on the other model, defaults to the underscored name of the current model suffixed by _id

  • :references - Sets the key on the current model to be used for the association, defaults to the primary key on the model;

Examples

defmodule Post do
  schema "posts" do
    has_many :comments, Comment
  end
end

# Get all comments for a given post
post = Repo.get(Post, 42)
comments = Repo.all assoc(post, :comments)

# The comments can come preloaded on the post struct
[post] = Repo.all(from(p in Post, where: p.id == 42, preload: :comments))
post.comments #=> [ %Comment{...}, ... ]
Source
has_one(name, queryable, opts \\ [])

Indicates a one-to-one association with another model.

The current model has zero or one records of the other model. The other model often has a belongs_to field with the reverse association.

Options

  • :foreign_key - Sets the foreign key, this should map to a field on the other model, defaults to the underscored name of the current model suffixed by _id

  • :references - Sets the key on the current model to be used for the association, defaults to the primary key on the model

Examples

defmodule Post do
  schema "posts" do
    has_one :permalink, Permalink
  end
end

# The permalink can come preloaded on the post struct
[post] = Repo.all(from(p in Post, where: p.id == 42, preload: :permalink))
post.permalink #=> %Permalink{...}
Source
schema(source, opts \\ [], block)

Defines a schema with a source name and field definitions.

Source