1
votes

I have this function: I'm trying to compare to lists of records to see if there is a match between the two of them.

def current_user_has_team?(user, teams) do
  user = user |> Repo.preload(:teams)

  Enum.member?(user.teams, teams)
end

This is not working though because it's returning false when there is only one record and they are matching.

How can I say: "Look at this list of records, do any of these match within this other list?" in Elixir?

It would be this in Ruby:

list_1 = [1,2,3]
list_2 = [3,4,5]

(list_1 & list_2).any? => true
1

1 Answers

5
votes

To answer the original question, you can do this:

Enum.any?(user.teams, fn team -> team in teams end)

But a better way would be to use a different query - one which checks if any id of teams exists in user.teams:

def current_user_has_team?(user, teams) do
  ids = Enum.map(teams, & &1.id)
  !!Repo.one(from(team in assoc(user, :teams), where: team.id in ^ids, limit: 1))
end

The query will return nil if there's no match and the first matching team if there is. The !! will turn this into a boolean, which'll make a match return true and a non match return false.