I have a function in Elixir using Ecto that preloads associations for a given entity. The current implementation looks like this:
@spec get(integer() | String.t(), list()) :: t() | nil
def get(id, preloads \ []) do
Shop
|> Repo.get(id)
|> Repo.preload(preloads)
end
i use it like this:
Shop.get(id, [
:coustomers,
:products
])
and is it possible do make it like this ?:
Shop.get(id, [
:coustomers,
{:limit,:products,3}
])
2
Answers
It is possible to limit the number of preloaded records, but it takes more than a one liner and is maybe not as flexible as you would hope or expect:
Maybe you can create a function that takes a Module and a number (for the limit) and returns something identical to the
products_query
above, like:And use this as an argument for
Shop.get/2
:I would do something like this:
I have not tested this. It is just for illumination.