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