Prepare_changes: counter cache not update counter

Hi i’m doing a counter cache like explained here:
https://hexdocs.pm/ecto/Ecto.Changeset.html#prepare_changes/2

with this code:

|> prepare_changes(fn changeset -> assoc(changeset.data, :user) |> changeset.repo.update_all(inc: [comment_count: 1]) changeset end)

but it doesn’t work because the user_id in changeset.data is nil

I have to do this for fix it:
.. |> prepare_changes(fn changeset -> from(p in User, where: p.id == ^get_field(changeset, :user_id)) |> changeset.repo.update_all(inc: [comment_count: value]) changeset end) ...
Now it works. But i would know why the example’s ecto guide not works.

Thanks

In the ecto example there is a post_id passed in with the cast() function, and so a post_id is available in the example, and so the assoc function does its job.