szajbus
Pattern match to check if association is preloaded
Hi, I’m wondering if the following is a viable approach.
def followed_by?(%{followers: followers}, user) when is_list(followers) do
followers
|> Enum.any?(fn follower ->
follower.id == user.id
)
end
def followed_by?(offer, user) do
offer
|> assoc(:followers)
|> where(user_id: ^user.id)
|> Repo.exists?()
end
Depending on the context, an offer may or may not have the followers association preloaded.
Pattern matching is used to check this, so that I can avoid unneeded database query when it actually is preloaded.
My doubt is about the guard: is is_list a good approach here?
It obviously works, because %Ecto.Association.NotLoaded{} is not a list and since it’s a has_many assoctiation, it produces a list when loaded.
But how about the readability/understandability?
Marked As Solved
blatyo
I’d probably reverse it and match on %Ecto.Association.NotLoaded{}, because it would be clearer to me.
Also Liked
thomasbrus
Another thing to think about.. I think the first function knows a bit too much.
It reaches into the %Offer{} which happens to have followers preloaded, and thats why it works. Imagine %Offer{} had other associations that may or may not be preloaded but are needed by followed_by?. Then the pattern matching would have to take into account all these different scenarios.
Perhaps you can accomplish this in a different way (while still efficient). Let’s say you have a show page on which you show 1 offer. Then you can simply use the followed_by?(offer, user) you already have (2nd function).
But then perhaps there’s an index page with a list of offers which preloads followers (I assume). In that case I would perform an additional query: offers_followed_by_user(user). It can just return the ids of the offers for example. Then it is straightforward and efficient to check if a certain offer on the index page is followed by the user (offer.id in offers_followed_by_user).
thomasbrus
There is also Ecto.assoc_loaded?/1. But you can’t use it as a guard.
Also in terms of readability def followed_by?(%Offer{followers: .. } is a bit easer to follow I think.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









