Upsert in Rails ActiveRecord
There is an awesome new feature in rails 6: they added upsert
and upsert_all
to ActiveRecord
More info can be found here https://edgeapi.rubyonrails.org/classes/ActiveRecord/Persistence/ClassMethods.html#method-i-upsert_all
Model.find_or_initialize
likely does what you want. You can chain it with save
or update_attributes
if that makes sense.
More info in the Rails Guides.