File tree Expand file tree Collapse file tree 2 files changed +19
-1
lines changed
Expand file tree Collapse file tree 2 files changed +19
-1
lines changed Original file line number Diff line number Diff 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
Original file line number Diff line number Diff 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
You can’t perform that action at this time.
0 commit comments