Skip to content

Instantly share code, notes, and snippets.

@zilkey
Created December 16, 2013 22:00
Show Gist options
  • Save zilkey/7995215 to your computer and use it in GitHub Desktop.
Save zilkey/7995215 to your computer and use it in GitHub Desktop.
save or destroy multiple objects in a transaction and return false if any one of them doesn't work
def save_objects(*objects)
success = false
ActiveRecord::Base.transaction do
results = objects.map do |object|
if object && !object.marked_for_destruction?
object.save
elsif object
object.destroy
else
true
end
end
success = results.all? { |saved| saved }
raise ActiveRecord::Rollback unless success
end
success
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment