Why `Repo.preload` has the `:force` option?

ecto

#1

Does anyone know the rationale behind the decision for preload to not reload an association already loaded, and thus, require passing force: true to reload it?

I ask this question because I imagine that if someone calls preload for a loaded association it is only for the sake of refreshing the association, e.g., to get newly associated elements or a different subset of these, and in both cases the preload must interrogate the database.

I must be missing some use case here that justifies having this option. What is it?

Thanks


#2

Imho the much more likely use-case for preloads on existing assocs is functional composition, where some assocs might just be loaded in multiple places, because of different code paths of items. And there’s no point in reloading things if they’re already loaded. The only use for force: true I have is in tests with factories not getting their assocs assigned correctly.


#3

Thanks for your response.

Avoiding association reload due to functional composition makes sense, as you say, if the association is manipulated everywhere as a whole; otherwise force: true is necessary if the functions being composed preload and manipulate different subsets of the association.


#4

Yep. But I’d imagine that’s the more advanced use-case which warrants the more explicit way of saying you’re loading new data. Also ecto is generally quite concerned with assocs not being automatically loaded anywhere, so the explicit option makes sense in that way as well.


#5

It is important to know the rationale behind these decisions to best understand how to use the Ecto API.

Thanks