2 title: "Phoenix: Ecto models"
7 This is for Phoenix 1.2 and below. [Phoenix 1.3 has a new API.](phoenix-ecto@1.3.html).
12 $ mix phoenix.gen.html Profile profiles email:string age:integer
13 $ mix phoenix.gen.html User users email:string hashed_password:string
25 # :id :binary :integer :float :boolean :string :binary
26 # {:array, inner_type} :decimal :map
28 field :password, virtual: true
36 def changeset(user, params \\ :empty) do
38 |> Ecto.Changeset.change # basic casting to changeset
41 |> cast(params, ~w(name email), ~w(age)) # params to Changeset
43 |> validate_format(:email, ~r/@/)
45 |> validate_inclusion(:age, 18..100)
46 |> validate_exclusion(:role, ~w(admin superadmin))
47 |> validate_subset(:pets, ~w(cat dog parrot whale))
49 |> validate_length(:body, min: 1)
50 |> validate_length(:body, min: 1, max: 160)
51 |> validate_length(:partners, is: 2)
53 |> validate_number(:pi, greater_than: 3)
54 |> validate_number(:pi, less_than: 4)
55 |> validate_number(:pi, equal_to: 42)
57 |> validate_change(:title, fn _, _ -> [])
58 |> validate_confirmation(:password, message: "does not match")
60 |> unique_constraint(:email)
61 |> foreign_key_constraint(:post_id)
62 |> assoc_constraint(:post) # ensure post_id exists
63 |> no_assoc_constraint(:post) # negative (useful for deletions)
69 changeset.errors #=> [title: "empty"]
71 changeset.changes #=> %{}
72 changeset.params[:title]
74 changeset.required #=> [:title]
75 changeset.optional #=> [:body]
82 |> change(title: "New title")
83 |> change(%{ title: "New title" })
84 |> put_change(:title, "New title")
85 |> force_change(:title, "New title")
86 |> update_change(:title, &(&1 <> "..."))
88 |> delete_change(:title)
89 |> merge(other_changeset)
91 |> add_error(:title, "empty")
97 get_change(changeset, :title) #=> "hi" (if changed)
98 get_field(changeset, :title) #=> "hi" (even if unchanged)
100 fetch_change(changeset, :title) #=> {:ok, "hi"} | :error
101 fetch_field(changeset, :title) #=> {:changes | :model, "value"} | :error
110 Repo.get_by(User, email: "john@hello.com") #=> %User{} | nil
118 changeset |> Repo.update
119 changeset |> Repo.insert
120 changeset |> Repo.insert_or_update
125 |> Ecto.Changeset.change(%{name: "hi"})
135 where: p.title == "Hello",
136 where: [state: "Sweden"],
142 order_by: [c.name, c.title],
143 order_by: [asc: c.name, desc: c.title],
145 preload: [:comments],
146 preload: [comments: {c, likes: l}],
148 join: c in assoc(c, :comments),
149 join: p in Post, on: c.post_id == p.id,
153 select: {p.title, p.description},
154 select: [p.title, p.description],
166 Repo.update_all(Post, set: [title: "Title"])
167 Repo.update_all(Post, inc: [views: 1])
170 ### Chaining `_all` with queries
173 from(p in Post, where: p.id < 10)
174 |> Repo.update_all(...)
176 from(p in Post, where: p.id < 10)