BeniaminoBaggins
BeniaminoBaggins

Reputation: 12433

Error inserting multiple rows into a PostgreSQL Ecto database using a changeset

I have this function to insert all categories into a productCategory table for a specific product.

EG one product has many categories.

In repo.ex

  def insertProductCategories(conn, product, productId) do 
    IO.inspect(product)
    changeset = Enum.each(product["categories"], fn (productCategory) -> 
       Api.ProductCategory.changeset(%Api.ProductCategory{c_id: productCategory["value"], p_id: productId})
    end)

    errors = changeset.errors
    valid = changeset.valid?
    case insert(changeset) do
      {:ok, product} ->
        conn
          |> put_resp_content_type("application/json")
          |> send_resp(200, Poison.encode!(%{
              successs: product
          }))
      {:error, changeset} ->

        conn
          |> put_resp_content_type("application/json")
          |> send_resp(500, Poison.encode!(%{
              failure: changeset
          }))
    end
  end

productCategory.ex

defmodule Api.ProductCategory do
  use Ecto.Schema
  @derive {Poison.Encoder, only: [:c_id, :p_id]}
  schema "productCategories" do
    field :c_id, :integer
    field :p_id, :integer
  end

  def changeset(productCategory, params \\ %{}) do
    productCategory
    |> Ecto.Changeset.cast(params, [:c_id, :p_id])
    |> Ecto.Changeset.validate_required([:c_id, :p_id])
  end
end

This is the 2 things that log to the console when insertProductCategories runs for - the inspection of a product, and the error:

%{"brand" => "Healtheries",
  "categories" => [%{"categoryId" => 1, "label" => "Meat",
     "selectedAdd" => true, "selectedSearch" => false, "value" => 1},
   %{"categoryId" => 1, "label" => "Dairy", "selectedAdd" => true,
     "selectedSearch" => false, "value" => 2},
   %{"categoryId" => 1, "label" => "Confectionary", "selectedAdd" => true,
     "selectedSearch" => false, "value" => 3},
   %{"categoryId" => 1, "label" => "Dessert", "selectedAdd" => true,
     "selectedSearch" => false, "value" => 4},
   %{"categoryId" => 1, "label" => "Baking", "selectedAdd" => true,
     "selectedSearch" => false, "value" => 5},
   %{"categoryId" => 1, "label" => "Condiments", "selectedAdd" => true,
     "selectedSearch" => false, "value" => 6},
   %{"categoryId" => 1, "label" => "Beverages", "selectedAdd" => true,
     "selectedSearch" => false, "value" => 7}],
  "description" => "Yummy chocolate bits for baking", "image" => "no-image",
  "name" => "Chocolate Bits"}

20:49:46.103 [error] #PID<0.340.0> running Api.Router terminated
Server: 192.168.20.3:4000 (http)
Request: POST /products
** (exit) an exception was raised:
    ** (UndefinedFunctionError) function :ok.errors/0 is undefined (module :ok is not available)
        :ok.errors()
        (api) lib/api/repo.ex:33: Api.Repo.insertProductCategories/3
        (api) lib/api/router.ex:1: Api.Router.plug_builder_call/2
        (api) lib/plug/debugger.ex:123: Api.Router.call/2
        (plug) lib/plug/adapters/cowboy/handler.ex:15: Plug.Adapters.Cowboy.Handler.upgrade/4
        (cowboy) /Users/Ben/Development/Projects/vepo/api/deps/cowboy/src/cowboy_protocol.erl:442: :cowboy_protoco
l.execute/4

I have only ever done this for a database insertion of more than 1 row but it doesn't have any validation:

Enum.each(subcategories, fn (subcategory) -> insert(subcategory) end)

And I have only used a changeset with validation for a one row insertion:

def insertProduct(conn, product) do
    changeset = Api.Product.changeset(%Api.Product{}, product)
    errors = changeset.errors
    valid = changeset.valid?
    case insert(changeset) do
      {:ok, product} ->
        conn
          |> put_resp_content_type("application/json")
          |> send_resp(200, Poison.encode!(%{
              successs: product
          }))
      {:error, changeset} ->

        conn
          |> put_resp_content_type("application/json")
          |> send_resp(500, Poison.encode!(%{
              failure: changeset
          }))
    end
  end

I'm trying to merge these techniques. I would like to keep the validation code in there (eg the case for :ok and :error but am unsure how to do that when I am inserting more than one row into the database. What am I doing wrong?

Upvotes: 0

Views: 884

Answers (2)

chrismcg
chrismcg

Reputation: 1286

I think you need Enum.map in repo.ex, not Enum.each.

From the docs:

each(enumerable, fun)
each(t, (element -> any)) :: :ok
Invokes the given fun for each item in the enumerable.

Returns :ok.

Which is why you're seeing the function :ok.errors/0 is undefined

Upvotes: 0

Dogbert
Dogbert

Reputation: 222148

You can use Ecto.Multi to sequence insertions for a bunch of changesets, and then run it in a transaction. The transaction will make sure that if there's any error in any insertion, the rest of the changes get rolled back.

multi = Enum.reduce(Enum.with_index(product["categories"]), Ecto.Multi.new, fn {productCategory, index}, multi -> 
   changeset = Api.ProductCategory.changeset(%Api.ProductCategory{c_id: productCategory["value"], p_id: productId})
   Ecto.Multi.insert(multi, index, changeset)
end)

case Repo.transaction(multi) do
  {:ok, categories} ->
    # categories here is a map with the index as key and struct as value
    ...
  {:error, failed_operation, failed_value, changes_so_far} ->
    ...
end

You can read more about the values returned by Repo.transaction for Ecto.Multi in this example in the documentation and the documentation of Ecto.Repo.transaction/2.

Upvotes: 1

Related Questions