Schema
Schema (Structs)
Default id of type integer and timestamps() creates inserted/updated at field.
defmodule User do
use Ecto.Schema
@derive {Jason.Encoder, only: [:name, :age, :company_id]} #for sending %User through HTTP requests
schema "users" do #users is table name
field :name, :string
field :age, :integer, default: 0
field :links, {:array, :string}
has_many :posts, Post
belongs_to :company, MyApp.Company
end
end
defmodule Comment do
use Ecto.Schema
schema "comments" do
field :content, :string
field :parent_id, :integer
belongs_to :parent, Comment, foreign_key: :id, references: :parent_id, define_field: false
has_many :children, Comment, foreign_key: :parent_id, references: :id
end
endFinally, schemas can also have virtual fields by passing the virtual: true option.
Example
Simple User
Password Hash Example
User Context with this Schema
Extra
lib/hello/repo.ex
Changeset
Last updated