Rails 6 upsert_all
Rails 6 and ActiveRecord introduces upsert_all 🎉
I used to have to jump into SQL and write this myself, but no more!
As a simplified use case, say you have a User
and that user has many Tag
s. If an API wants to send you an array of strings (["Tag Name A", "Tag Name B"]
), you no longer have to do any looping, find_or_create
, or defining your own upsert in SQL nonsense.
@user.tags << Tag.upsert_all([
{ name: "Tag Name A"},
{ name: "Tag Name B"}
], unique_by: :name)
If the tags exist, they will be updated. If the tags are new, they will be created. And all this happens in 1 SQL Insert.
Tweet