Peter Marklund

Peter Marklund's Home

Thu Sep 06 2007 07:33:04 GMT+0000 (Coordinated Universal Time)

Rails and Transactional Saves

Correction: ActiveRecord::Base#save does use transactions in Rails by default, see Jarkkos comment.

In Rails, models are not saved within a database transaction by default. This means that if you are updating some other record in a callback like after_save then the record will still be saved even if an exception is raised in the callback. If you care a lot about data integrity this is not satisfactory. One way to remedy the problem might be to simply override the save and save! methods in your model like this:

  def save
    Post.transaction { super }
  end

  def save!
    Post.transaction { super }
  end

That's the workaround I'm going to use for now.