Created
December 16, 2013 22:00
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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