Skip to content

Commit

Permalink
Improve error messages for invalid assocs, closes #3333
Browse files Browse the repository at this point in the history
  • Loading branch information
josevalim committed Jun 14, 2020
1 parent e75ae55 commit a522ff0
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 12 deletions.
4 changes: 3 additions & 1 deletion lib/ecto/changeset.ex
Original file line number Diff line number Diff line change
Expand Up @@ -862,8 +862,10 @@ defmodule Ecto.Changeset do

defp relation!(_op, type, _name, {type, relation}),
do: relation
defp relation!(op, :assoc, name, nil),
do: raise(ArgumentError, "cannot #{op} assoc `#{name}`, assoc `#{name}` not found. Make sure it is spelled correctly and that the association type is not read-only")
defp relation!(op, type, name, nil),
do: raise(ArgumentError, "cannot #{op} #{type} `#{name}`, assoc `#{name}` not found. Make sure it is spelled correctly and properly pluralized (or singularized)")
do: raise(ArgumentError, "cannot #{op} #{type} `#{name}`, #{type} `#{name}` not found. Make sure that it exists and is spelled correctly")
defp relation!(op, type, name, {other, _}) when other in @relations,
do: raise(ArgumentError, "expected `#{name}` to be an #{type} in `#{op}_#{type}`, got: `#{other}`")
defp relation!(op, type, name, schema_type),
Expand Down
13 changes: 2 additions & 11 deletions lib/ecto/schema.ex
Original file line number Diff line number Diff line change
Expand Up @@ -847,17 +847,6 @@ defmodule Ecto.Schema do
post = Repo.get(Post, 42)
authors = Repo.all assoc(post, :comments_authors)
Although we used the `:through` association in the example above, Ecto
also allows developers to dynamically build the through associations using
the `Ecto.assoc/2` function:
assoc(post, [:comments, :author])
In fact, given `:through` associations are read-only, **using the `Ecto.assoc/2`
format is the preferred mechanism for working with through associations**. Use
the schema-based one only if you need to store the through data alongside of
the parent struct, in specific cases such as preloading.
`:through` associations can also be preloaded. In such cases, not only
the `:through` association is preloaded but all intermediate steps are
preloaded too:
Expand All @@ -882,6 +871,8 @@ defmodule Ecto.Schema do
[comment] = Repo.all(Comment) |> Repo.preload(:post_permalink)
comment.post_permalink #=> %Permalink{...}
Note `:through` associations are read-only. For example, you cannot use
`Ecto.Changeset.cast_assoc/3` to modify through associations.
"""
defmacro has_many(name, queryable, opts \\ []) do
queryable = expand_alias(queryable, __CALLER__)
Expand Down

0 comments on commit a522ff0

Please sign in to comment.