[Proposal] Support `through` via `belongs_to` association

383 views
Skip to first unread message

tom.cr...@gmail.com

unread,
Sep 17, 2020, 4:21:34 AM9/17/20
to elixir-ecto
Currently the through option is only supported via has_one and has_many associations, but not via belongs_to associations. Would make sense to support this too? For example:

schema "chapter" do
  # ...
  belongs_to(:book, Book)
end

schema "page" do
  # ...
  belongs_to(:chapter, Chapter)
  belongs_to(:book, through: [:chapter, :book])
end

What do you think?

José Valim

unread,
Sep 17, 2020, 4:25:51 AM9/17/20
to elixi...@googlegroups.com
You can use has_one for the exact same behaviour. belongs_to assumes that the current schema will have the foreign key for the association, which is not the case here. :)

--
You received this message because you are subscribed to the Google Groups "elixir-ecto" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-ecto...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-ecto/9fbaf9a7-204b-464c-91e5-5da468d3afa0n%40googlegroups.com.

tom.cr...@gmail.com

unread,
Sep 17, 2020, 4:35:20 AM9/17/20
to elixir-ecto
That's what I tried initially, but if you use has_one via a belongs_to, we get the following:

(ArgumentError) schema does not have the association :chapter used by association :book, please ensure the association exists and is defined before the :through one

Stacktrace:
  │ lib/ecto/association.ex:796: Ecto.Association.HasThrough.struct/3
  │ lib/ecto/schema.ex:1707: Ecto.Schema.association/5
  │ ...
  │ (stdlib 3.13) erl_eval.erl:680: :erl_eval.do_apply/6

tom.cr...@gmail.com

unread,
Sep 17, 2020, 4:43:03 AM9/17/20
to elixir-ecto
For example:

schema "chapter" do
  # ...
  belongs_to(:book, Book)
end

schema "page" do
  # ...
  belongs_to(:chapter, Chapter)
  has_one(:book, through: [:chapter, :book]) # this gives the ArgumentError
end

José Valim

unread,
Sep 17, 2020, 5:05:53 AM9/17/20
to elixi...@googlegroups.com
Perhaps the best option from now on is to make the above work. :)

tom.cr...@gmail.com

unread,
Sep 17, 2020, 5:16:54 AM9/17/20
to elixir-ecto
Sounds good to me... should I create an issue in github or does the proposal need to be "fleshed out" a bit?

José Valim

unread,
Sep 17, 2020, 5:49:09 AM9/17/20
to elixi...@googlegroups.com
Creating an issue is fine but someone would have to work on it at some point. :)

tom.cr...@gmail.com

unread,
Sep 17, 2020, 6:12:42 AM9/17/20
to elixir-ecto
Understood. I'll take a look at it and see if it's within my meagre capabilities :)

tom.cr...@gmail.com

unread,
Sep 17, 2020, 6:30:11 AM9/17/20
to elixir-ecto
Good news, it turns out has_one via a belongs_to actually works already, but it must be defined after the belongs_to in the schema. Obvious when you think about it.

Sorry for wasting your time Jose!

Reply all
Reply to author
Forward
0 new messages