How do I add a field to a changeset only if the field is not nil? I don't want to update the value in the database if the value is nil. I need to check 3 fields and only update the ones that are not nil.
current code:
put "/products" do
errors = {}
IO.inspect(conn.body_params)
product = Api.Product |> Api.Repo.get(conn.query_params["id"])
IO.inspect(product)
if conn.body_params["image"] do
changeset = Api.Product.changeset(product, %{image: conn.body_params["image"]})
end
if conn.body_params["description"] do
changeset = Api.Product.changeset(product, %{description: conn.body_params["description"]})
end
if conn.body_params["price"] do
changeset = Api.Product.changeset(product, %{price: conn.body_params["price"]})
end
case Api.Repo.update(changeset) do
{:ok, product} ->
errors = Tuple.append(errors, "Product updated")
{:error, changeset} ->
errors = Tuple.append(errors, "Product not updated")
end
conn
|> put_resp_content_type("application/json")
|> send_resp(200, Poison.encode!(%{
successs: "success",
errors: Tuple.to_list(errors)
}))
end