Ecto best practices covering preloading, schema types, changeset validation, field access, security, and migration conventions. Use when working with Ecto schemas, changesets, queries, or migrations.
# If the template needs message.user.email
messages = Repo.all(from m in Message, preload: [:user])
import Ecto.Query and other supporting modules when you write seeds.exsEcto.Schema fields always use the :string type, even for :text columns:field :name, :string
field :description, :string # Even if the DB column is :text
Ecto.Changeset.validate_number/2 DOES NOT SUPPORT the :allow_nil option. By default, Ecto validations only run if a change for the given field exists and the change value is not nil, so such an option is never neededEcto.Changeset.get_field(changeset, :field) to access changeset fieldschangeset[:field]) on changesetsuser_id, must not be listed in cast calls or similar for security purposes. Instead they must be explicitly set when creating the struct:# GOOD: Set user_id explicitly, not through cast
%Message{}
|> Message.changeset(params) # cast only includes :content, :subject, etc.
|> Ecto.Changeset.put_assoc(:user, user)
mix ecto.gen.migration migration_name_using_underscores when generating migration files, so the correct timestamp and conventions are applied