elixirphoenix-frameworkelixir-poison

How to add an item to list in cycle in Elixir/Phoenix


I'm studying Elixir/Phoenix and there is a task in front of me. I need to filter results from database in a cycle. Something like this:

user = Repo.get_by(User, api_token: token)
rooms = Repo.all(Room)
result = []
if !Enum.empty?(rooms) do
  Enum.each rooms, fn room ->
    users = Poison.decode!(room.users)
    if Enum.member?(users, user.id) do
       result = result ++ [room]
    end
  end
end
json(conn, %{"rooms" => result})

But this case don't allow me to append items to list, why? Because this is a functional language... Is there a way to append items to list in a cycle?

Oh yeah, maybe you ask me "Why you just don't get objects from the database by user id?" I'll say that the room.users store json array encoded in string


Solution

  • Whenever you want to select some items from a list, you can use Enum.filter/2. You can also use the in operator instead of Enum.member?/2.

    user = Repo.get_by(User, api_token: token)
    rooms = Repo.all(Room)
    result = Enum.filter(rooms, fn room ->
      user.id in Poison.decode!(room.users)
    end)
    

    You can also use for instead of Enum.filter/2:

    result = for room <- rooms, user.id in Poison.decode!(room.users), do: room