Counter cache in 2022

Searching the web on how does one “properly” do the equivalent of the two words counter_cache: true clause from “the other framework” I found posts like:

They’re surely more than enough to get me started, yet the question is if anything maybe changed since 2016 in the Elixir/Phoenix world in regards to counter caching? Any new patterns/functions/… emerged? Or do those posts still represent the state of the union today?

Update: I also found:

https://hexdocs.pm/ecto/Ecto.Changeset.html#prepare_changes/2-example

which suggests it all remains valid but if anyone has other interesting approaches, please share :wink:

EDIT: Thanks @silverdr, didn’t read the whole past :man_facepalming: For posterity:

Oof, that blog post is not doing the same thing as the changeset example. The blog post increments the counter any time changeset is called, even if the changeset has errors and won’t persist. It also doesn’t do so transactionally.

Ecto.Changeset — Ecto v3.8.3 on the other hand adds the function to the changeset, so that it will be executed in the same transaction as the insertion, and only if it is successful.

If you mean the first one then it “corrects itself” later :wink: