Ecto associations and the purpose of has many through and many to many

In Ecto’s has_many docs section on the :through option:

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.

So, have you tried the assoc function?

1 Like