Hi,
I’m trying to insert a list of entities my using Enum.each
but I have problem with how to deal with it if some validation fails.
I have external parameters from frontend:
[%{"option_id" => 2, "poll_id" => 1}, %{"option_id" => 3, "poll_id" => 1}]
Then in my context
Enum.each(attrs, fn params ->
%Vote{}
|> Vote.changeset(params)
|> Repo.insert()
end)
When I look at the docs, Enum.each
returns an :ok
atom but what I want is to match the return with my controller.
def cast_vote(conn, %{"vote" => vote_params}) do
with {:ok, _vote} <- Polls.cast_vote(vote_params) do
send_resp(conn, :no_content, "")
end
end
I also want to return a 400 bad request when a validation error occurs in one of the elements of the list.