Performing Upserts with Schemas

Just 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.

To illustrate this difference, let’s reset our database with mix ecto.reset then try creating a new genre using the Genre struct:

  genre = %Genre{​name:​ ​"​​funk"​, ​wiki_tag:​ ​"​​Funk"​}
  Repo.insert(genre)
  #=> {:ok,
  #=> %MusicDB.Genre{__meta__: #Ecto.Schema.Metadata<:loaded, "genres">,
  #=> albums: #Ecto.Association.NotLoaded<association :albums is not loaded>,
  #=> id: 3, inserted_at: ~N[2018-03-05 14:26:13], name: "funk",
 

Get Programming Ecto now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.