Skip to content

Commit

Permalink
Do not assume all arguments in empty? are changesets
Browse files Browse the repository at this point in the history
Closes #2178
  • Loading branch information
José Valim committed Aug 23, 2017
1 parent 4f84ddf commit f8f3c1f
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib/ecto/changeset/relation.ex
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,12 @@ defmodule Ecto.Changeset.Relation do
"""
def empty?(%{cardinality: _}, %NotLoaded{}), do: true
def empty?(%{cardinality: :many}, []), do: true
def empty?(%{cardinality: :many}, changes), do: Enum.all?(changes, & &1.action in [:replace, :delete])
def empty?(%{cardinality: :many}, changes) do
Enum.all?(changes, fn
%Changeset{action: action} when action in [:replace, :delete] -> true
_ -> false
end)
end
def empty?(%{cardinality: :one}, nil), do: true
def empty?(%{}, _), do: false

Expand Down
5 changes: 5 additions & 0 deletions test/ecto/changeset/has_assoc_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,11 @@ defmodule Ecto.Changeset.HasAssocTest do
assert changeset.changes == %{}
assert changeset.errors == [posts: {"can't be blank", [validation: :required]}]

changeset = cast(%Author{posts: [%Post{title: "hello", id: 1}]}, %{}, :posts, required: true)
assert changeset.required == [:posts]
assert changeset.changes == %{}
assert changeset.errors == []

changeset = cast(%Author{posts: []}, %{"posts" => nil}, :posts, required: true)
assert changeset.required == [:posts]
assert changeset.changes == %{}
Expand Down

0 comments on commit f8f3c1f

Please sign in to comment.