Multi operations and Transactions
Crecto provides the Multi
class, for utilizing database transactions.
With Multi
, if any step of the transaction fails then all changes are rolled back.
As with Query
, its easiest to create a shortcut variable.
Multi = Crecto::Multi
Multi
example and methods
First create the multi intance
multi = Multi.new
Build the multi with the needed database operations
# Create the multi instancemulti = Multi.new
# Insert a new recordmulti.insert(new_user)
# Delete an recordmulti.delete(image)
# Delete allmulti.delete_all(Comment)
# Update a recordmulti.update(post)
# Update allmulti.update_all(User, Query.where(name: "Shaquille"), {name: "RuPaul"})
Insert the multi using your Repo
MyRepo.transaction(multi)
Check the multi for errors. If there were errors on any of the operations, then none of the operations will be persisted.
if multi.errors.any? puts "good to go"else puts "woops"end