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"​}
  #=> {: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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.