Skip to content

Commit cba4947

Browse files
authored
Update Ecto.Changeset.get_assoc/3 typespecs (#4495)
1 parent 9df9b35 commit cba4947

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

lib/ecto/changeset.ex

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1689,7 +1689,8 @@ defmodule Ecto.Changeset do
16891689
[%Post{id: 1, title: "world"}]
16901690
16911691
"""
1692-
@spec get_assoc(t, atom, :changeset | :struct) :: [t | Ecto.Schema.t()]
1692+
@spec get_assoc(t, atom, :changeset | :struct) ::
1693+
[t | Ecto.Schema.t()] | t | Ecto.Schema.t() | nil
16931694
def get_assoc(changeset, name, as \\ :changeset)
16941695

16951696
def get_assoc(%Changeset{} = changeset, name, :struct) do

test/ecto/changeset_test.exs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -930,6 +930,23 @@ defmodule Ecto.ChangesetTest do
930930
]
931931

932932
assert get_assoc(base_changesset, :comments, :struct) == [%Comment{id: 123}]
933+
934+
# for a "belongs to" assoc, get_assoc returns the changeset directly
935+
comment_with_post_changeset = change(%Comment{post: %Post{}})
936+
assert get_assoc(comment_with_post_changeset, :post, :changeset) == change(%Post{})
937+
assert get_assoc(comment_with_post_changeset, :post, :struct) == %Post{}
938+
939+
# empty/nil assoc behavior:
940+
941+
# for a "has many" assoc, get_assoc returns an empty list
942+
has_many_changeset = change(%Post{})
943+
assert get_assoc(has_many_changeset, :comments, :changeset) == []
944+
assert get_assoc(has_many_changeset, :comments, :struct) == []
945+
946+
# for a "belongs to" assoc, get_assoc returns nil
947+
belongs_to_changeset = change(%Comment{})
948+
assert get_assoc(belongs_to_changeset, :post, :changeset) == nil
949+
assert get_assoc(belongs_to_changeset, :post, :struct) == nil
933950
end
934951

935952
test "fetch_change/2" do

0 commit comments

Comments
 (0)