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.

begin
  transaction do
    first.save!
    second.save!
    third.save!
    fourth.save!
  end
rescue ActiveRecord::RecordInvalid => invalid
# do whatever you wish to warn the user, or log something
end

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

About these ads

  • My Open Source

  • Twitter Updates

    • @jc_quijano lo interesante será la reacción del cloud no-USA, porque la orden es para "any company with operations [in USA]" 14 hours ago
    • @jc_quijano supongo que se liará "a posteriori", en cuanto el juez decida (sobre todo si decide q MS debe dar el email). 14 hours ago
    • RT @geekgrrl: Cannot. Stop. Laughing. RT @lmorchard via @embee: what happens when non-tech people discover web developer tools http://t.co/… 1 day ago
    • Menos mal que hay sanidad pública… pero de parking me voy a dejar más de 100€ por no ser previsor (tenían abonos de 3 días x la mitad) 1 day ago
    • @nubeblog súper bien, mejor q con el hermano y ese ya fue estupendo. La madre está muy recuperada y @bmuino muy atento con su hermana 1 day ago
  • Enter your email address to follow this blog and receive notifications of new posts by email.

    Join 9 other followers

  • Flickr Photos

    Apertura Agile Open Spain 2011 - 32

    Apertura Agile Open Spain 2011 - 31

    Apertura Agile Open Spain 2011 - 30

    More Photos

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: