Performing Upserts Without Schemas

To practice upserts, let’s return to the genres table. This table is fairly small and has just two fields: name and wiki_tag. We can use the wiki_tag to create a link to the Wikipedia article so the user can learn more about the genre.

When we set up the table in our music_db database, we added a unique index on the name column. This ensures that we don’t accidentally set up two genres with the same name—we wouldn’t want to create two records for “jazz,” for example. We can use this unique index to help us with our upserts.

First, let’s use insert_all to create a new record for the “ska” genre:

  Repo.insert_all(​"​​genres"​, [[​name:​ ​"​​ska"​, ​wiki_tag:​ ​"​​Ska_music"​]]) ...

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.