Ecto ArgumentError: "comparison with nil is forbidden" when querying for null field in Phoenix/Elixir

The issue happens because one of the following values was nil: tournament_id or config_id. I added a guard clause to fix it to check that both inputs are valid strings before running the query. Here’s an example:

def get_active_instance(tournament_id, config_id)
      when is_binary(tournament_id) and is_binary(config_id) do
    Instance
    |> where(
      [i],
      i.tournament_id == ^tournament_id and
        i.config_id == ^config_id and
        is_nil(i.ended_at)
    )
    |> Repo.one()
    |> case do
      nil -> {:error, :no_active_tournament_instance}
      instance -> {:ok, instance}
    end
  end

The reason why it was confusing in the first place was that the Ecto query did not explicitly specify which value was trying to compare

1 Like