Unique constraint error while seeding

Hi,

Unique constraint on owner_name_index.

I would like to create a post in seeds file which belongs to an already created author.

This is the code I have in in my seeds file

defp create_post(owner) do
    attrs =
    Factory.post_factory()
    |> Map.from_struct()
    |> Map.put(:owner_id, owner.id)

    Posts.create_post(attrs)
  end

The factory for post:

def post_factory(attrs \\ %{}) do
    %Post{
      owner: attrs[:owner] || insert(:owner, prefix: "public"),
      title: attrs[:title] || "New title"
    }
  end

When I run seeds file, I get the unique constraint error. Any suggestion on how to avoid this?

In post_factory you look if attrs has an owner and if not (when nil), you insert an owner. Because you probably have a unique index on the name of an owner (meaning each owner cannot have the same name), it fails.

When you create your attrs , try passing in the owner like so:

attrs = 
  %{owner: owner} 
  |> Factory.post_factory()
  |> Map.from_struct()

This way uses the existing owner and does not try to create a new one.

OR

  1. you can generate a random name for the owner before you insert.
  2. remove the unique index on name (two or more people having the same name often)

@tomkonidas thanks for the quick response. I tried the first solution you gave

attrs = 
  %{owner: owner} 
  |> Factory.post_factory()
  |> Map.from_struct()
  |> Map.put(:owner_id: owner.id)

But I still see the same error. Unfortunately he second suggestion you gave doesn’t seem to work for my requirement.

what is owner before you pass it in to the factory?

Owner before passing into factory

%MyApp.Blog.Owners.Owner{
  __meta__: #Ecto.Schema.Metadata<:loaded, "public", "owner">,
  id: "1985c756-2592-4332-bb1d-3ed49ca3b35b",
  inserted_at: ~U[2022-04-07 22:02:36.797965Z],
  name: "owner1",
  prefix_name: "mp_$1$q9dv$$mk2$ud1_m0b_z59t$_",
  updated_at: ~U[2022-04-07 22:02:36.807815Z]
}

Is there a repo we can see? On the other hand why not use the build function directly? Looking at the ExMachina docs