Skip to content

Commit

Permalink
Update Ecto.Changeset.get_assoc/3 typespecs (#4495)
Browse files Browse the repository at this point in the history
  • Loading branch information
cserino committed Aug 17, 2024
1 parent 9df9b35 commit cba4947
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/ecto/changeset.ex
Original file line number Diff line number Diff line change
Expand Up @@ -1689,7 +1689,8 @@ defmodule Ecto.Changeset do
[%Post{id: 1, title: "world"}]
"""
@spec get_assoc(t, atom, :changeset | :struct) :: [t | Ecto.Schema.t()]
@spec get_assoc(t, atom, :changeset | :struct) ::
[t | Ecto.Schema.t()] | t | Ecto.Schema.t() | nil
def get_assoc(changeset, name, as \\ :changeset)

def get_assoc(%Changeset{} = changeset, name, :struct) do
Expand Down
17 changes: 17 additions & 0 deletions test/ecto/changeset_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -930,6 +930,23 @@ defmodule Ecto.ChangesetTest do
]

assert get_assoc(base_changesset, :comments, :struct) == [%Comment{id: 123}]

# for a "belongs to" assoc, get_assoc returns the changeset directly
comment_with_post_changeset = change(%Comment{post: %Post{}})
assert get_assoc(comment_with_post_changeset, :post, :changeset) == change(%Post{})
assert get_assoc(comment_with_post_changeset, :post, :struct) == %Post{}

# empty/nil assoc behavior:

# for a "has many" assoc, get_assoc returns an empty list
has_many_changeset = change(%Post{})
assert get_assoc(has_many_changeset, :comments, :changeset) == []
assert get_assoc(has_many_changeset, :comments, :struct) == []

# for a "belongs to" assoc, get_assoc returns nil
belongs_to_changeset = change(%Comment{})
assert get_assoc(belongs_to_changeset, :post, :changeset) == nil
assert get_assoc(belongs_to_changeset, :post, :struct) == nil
end

test "fetch_change/2" do
Expand Down

0 comments on commit cba4947

Please sign in to comment.