Reputation: 705
I want to save multiple objects, and rollback all if any of them fail. But I also want to render the ActiveRecord::RecordInvalid message so the user knows why it didn't save. How do I do this?
def save_multiple_things_or_error
ActiveRecord::Base.transaction do
thing_one.save!
thing_two.save!
rescue ActiveRecord::RecordInvalid => exception
# exception.message is what I want to render
raise ActiveRecord::Rollback
end
end
This doesn't work for a few reasons. I believe the rescue should be in a begin end block, but then if I raise the rollback, I lose the RecordInvalid exception.
Upvotes: 0
Views: 4484
Reputation: 2296
you could try this one:
begin
ActiveRecord::Base.transaction do
thing_one.save!
thing_two.save!
end
rescue => e
raise ActiveRecord::Rollback
end
this works fine for my situation
Upvotes: 3