Perform Upserts with Schemas

Learn how to perform upserts with schemas.

Create a new record using insert

Like insert_all, the insert function supports the on_conflict option for performing upserts. However, insert works with schema structs and the return value is different so we’ll have some extra considerations. Let’s see what this difference looks like exactly.

If you’ve been running these commands on your local setup, you should first run mix ecto.reset to reset the database. Let’s try creating a new genre using the Genre struct.

Press + to interact
genre = %Genre{name: "funk", wiki_tag: "Funk"}
Repo.insert(genre)
widget

Ecto successfully inserts the new record and returns :ok and our new database record as a Genre struct. We expect this, but it’s quite different from what insert_all gives us— a ...