Seeding database with unique assocs


is there a comfortable way to seed the database that has a table which associates a table with a unique constraint. I want to create or use my assocs on-the-fly

%{length: 11, 
  width: 20, 
  bg_color: %{color: "red"}, 
  border_color: %{color: "red"}

When I cast_assoc my association bg_color is inserted into the Color table, but when casting the border_color, I get a unique-constraint error.

Sure, I could create all colors beforehand and then just put_assoc them, but that’s not so convenient to handle with Ids.

I wrote a function get_or_insert() which I use like that:

%{length: 11, 
  width: 20, 
  bg_color: Color.get_or_insert(color: "red"), 
  border_color: get_or_insert(color: "red")

But I ask myself if there’s a builtin Ecto way to do this?

You can try to using the insert_all with the on_conflict option to trigger the upsert behavior.

You can se the documentation here:

Best regards,

1 Like