Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exclude through associations from __schema__(:associations) #3333

Closed
Adzz opened this issue Jun 14, 2020 · 2 comments
Closed

Exclude through associations from __schema__(:associations) #3333

Adzz opened this issue Jun 14, 2020 · 2 comments

Comments

@Adzz
Copy link
Contributor

Adzz commented Jun 14, 2020

Precheck

Environment

  • Elixir version (elixir -v): Elixir 1.10.2 (compiled with Erlang/OTP 22)
  • Ecto version (mix deps): 3.4.4
  • Database adapter and version (mix deps):

Current behavior

Currently if you try to cast a through association you get the following (somewhat misleading) error message:

defmodule Like do
  use Ecto.Schema
  schema "likes" do
    field(:up, :boolean)
  end
end

defmodule Comment do
  use Ecto.Schema
  schema "comments" do
    has_many(:likes, Like)
  end
end

defmodule Post do
 use Ecto.Schema
  schema "posts" do
    has_many(:comments, Comment)
    has_many(:comment_likes, through: [:comments, :like])
  end
end

Ecto.Changeset.cast(%Post{}, %{}, Post.__schema__(:fields)) 
|> Ecto.Changeset.cast_assoc(:comment_likes)
** (ArgumentError) cannot cast assoc `comment_likes`, assoc `comment_likes` not found. Make sure it is spelled correctly and properly pluralized (or singularized)

I think I can see why you can't cast_assoc a through association (though I think we could improve the error message!), but this trips me up when I try to automatically cast all associations with reflection.

Essentially if I do this: Post.__schema__(:associations) to find all of the associations that I need to cast, comment_likes is in the list.

The only way I can think to get this information right now is to use __changeset__ to figure out the list of associations, but that takes a lot more work.

Expected behavior

I'm not sure whether we could:

  1. Add a reflection mechanism for through associations, so I can filter them out.
    or
  2. Exclude through associations from __schema__(:associations)
    and / or
  3. improve the error message.
@josevalim
Copy link
Member

Use __schema__(:associations) and then check if the association is in __changeset__. That should fix your case. I will work on improving the error message. Thanks!

@Adzz
Copy link
Contributor Author

Adzz commented Jun 14, 2020

Thanks José!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants