I seriously struggle with Enum.reduce. I just can’t get my head wrapped around it but I know it is a valuable tool and I’m determined to understand it better.
I’m trying to write a function that uses it to run Repo.preload on a map based on a list of specified preloads.
So I have a map that is an Event with a bunch of fields and many relationships. When I call get_event, I don’t want to always preload everything. I want to pass the event_id and a preload_list of the relationships to preload:
So a preload list would look like this:
[:group, :users, :parent, :reminders]
Here’s the first Enum.reduce function I wrote (which throws errors):
def get_event(id, preload_list) do event = Repo.get(Event, id) Enum.reduce(preload_list, event, fn -> preload, event -> Repo.preload(event, preload) end) end
Preload is essentially “x” and event is “acc”. It says "syntax error before the comma between Preload and Event … but I’m giving it the parameters specified in Enum.reduce(enumerable, acc, fun).
OK … so then I tried this:
def get_event(id, preload_list) do event = Repo.get(Event, id) Enum.reduce(preload_list, event, fn -> :group, event -> Repo.preload(event, :group) :users, event -> Repo.preload(event, :users) :reminders, event -> Repo.preload(event, :reminders) :parent, event -> Repo.preload(event, :parent) end) end
Threw the same error. What am I doing wrong? Is the problem that I can’t use a map as an “acc” or that I can’t pass atoms as “x”?
Feel free to tell me if I’m approaching this in the totally wrong way and using the wrong Enum. Certainly won’t be the first time I went down the wrong path! LOL. I just thought Enum.reduce might be the right path since it accumulates the results.