Saving different Active Record classes in a single transaction

I’ve been getting in and out of rails development for some time now… and my biggest problem is finding documentation for simple things (I guess that people already know all the stuff, but I’m still getting up to speed).

So I decided to blog about one of those simple things… in case there is still someone who has not mastered Ruby on Rails.

When several models are saved in a single transaction in Rails, the usual case is that you want to rollback the transaction if any of them fails. This is done automatically if an exception is thrown.

The example in ActiveRecord::Transactions::ClassMethods accomplishes this by using save! on the models.

However, you usually also want to display validation errors and not show the full rails trace to the user.

What the example does not show is how to accomplish this. Two options here:

  1. use save (no exclamation mark) and check the return value. If any of the saves return false, raise an ActiveRecord::RollbackException after your render or redirect.
  2. rescue from ActiveRecord::RecordInvalid and render or redirect there.

I think #2 is more elegant… but since I knew about it too late, my code uses #1.

  transaction do!!!!
rescue ActiveRecord::RecordInvalid => invalid
# do whatever you wish to warn the user, or log something

Example is from this other blog post. I wish I’ve read it sooner!


  • My Open Source

  • Twitter Updates

    • @micho Infovia anyone? 2 hours ago
    • After days in Elixir, I write Ruby like: class Scoped.Thing do def baz do do_something() end end And wonder why it doesn’t parse 7 hours ago
    • RT @islomar: A piece of advice for anyone applying for a job: clearly transmit your MOTIVATIONS, GOALS and WHYS, not just a bunch of topics… 11 hours ago
    • RT @realntl: @wycats We want to say "sorry mgmt, we made a mess and need time to rewrite" but "the lang/framework sucks and we need to migr… 21 hours ago
    • @MarkVillacampa Al menos con todo esto, alguna gente aprenderá a actualizarse y por qué. Sobre todo la oposición! 21 hours ago
  • Enter your email address to follow this blog and receive notifications of new posts by email.

    Join 9 other followers

  • Flickr Photos

%d bloggers like this: