Search code examples
elixirecto

elixir - Ecto changeset success and failure code no longer running


This code used to add strings to the messages variable and then send them back in the http response. Now nothing gets added to the messages variable. The lines of code inside the :ok and :error blocks no longer runs. Where should I be dealing with the error and success case now, to add the messages on error and on success?

  messages = {}

  changeset = Api.UserProduct.changeset(
    user_product, %{:voted_vegan => true}
  )

  case Api.Repo.update(changeset) do
      {:ok, product} -> 
        IO.puts("appending messages7")
        messages = Tuple.append(messages, "Product updated")
      {:error, changeset} -> 
        IO.puts("appending messages8")
        messages = Tuple.append(messages, "Product not updated")
  end

  conn
      |> put_resp_content_type("application/json")
      |> send_resp(200, Poison.encode!(%{
          successs: "success",
          errors: Tuple.to_list(messages)
      }))

Solution

  • Your case expression has not side effect, you should assign the returned value of the case expression (which will be the value of the last expression in the executed branch) to messages variable.

    messages = {}
    
    changeset =
      Api.UserProduct.changeset(
        user_product,
        %{:voted_vegan => true}
      )
    
    messages =
      case Api.Repo.update(changeset) do
        {:ok, product} ->
          IO.puts("appending messages7")
          Tuple.append(messages, "Product updated")
    
        {:error, changeset} ->
          IO.puts("appending messages8")
          Tuple.append(messages, "Product not updated")
      end
    
    conn
    |> put_resp_content_type("application/json")
    |> send_resp(
      200,
      Poison.encode!(%{
        successs: "success",
        errors: Tuple.to_list(messages)
      })
    )