This page contains automated test results for code from O'Reilly's Ruby Cookbook. If this code looks interesting or useful, you might want to buy the whole book.

Using Transactions in ActiveRecord
CodeExpectedActual
require 'cookbook_dbconnect'
activerecord_connect # See chapter introduction
class User < ActiveRecord::Base
  has_and_belongs_to_many :blog_posts
end
class BlogPost < ActiveRecord::Base
  has_and_belongs_to_many :authors, :class_name => 'User'
end
require 'active_record/transactions'
class BlogPost
  def BlogPost.create_from_new_author(author_name, title, content)
    transaction do
      author = User.create(:name => author_name)
      raise 'Random failure!' if rand(2) == 0
      create(:authors => [author], :title => title, :content => content)
    end
  end
end
BlogPost.create_from_new_author('Carol', 'The End Is Near', 
                                'A few more facts of doom...')
#<BlogPost:0xb78b7c7c ... > #<BlogPost:0xb77ea8d4 @new_record_before_save=true, @errors=#<ActiveRecord::Errors:0xb77e8930 @errors={}, @base=#<BlogPost:0xb77ea8d4 ...>>, @attributes={"title"=>"The End Is Near", "id"=>16, "content"=>"A few more facts of doom..."}, @authors=[#<User:0xb77ecaf8 @new_record_before_save=true, @errors=#<ActiveRecord::Errors:0xb77ebc5c @errors={}, @base=#<User:0xb77ecaf8 ...>>, @attributes={"name"=>"Carol", "id"=>22}, @new_record=false>], @new_record=false>
User.find(:first, :conditions=>"name='Carol'")
#<User:0xb7888ae4 @attributes={"name"=>"Carol", ... }> #<User:0xb77e3534 @attributes={"name"=>"Carol", "id"=>"2"}>
BlogPost.create_from_new_author('David', 'The End: A Rebuttal', 
                                'The end is actually quite far away...')
RuntimeError: Random failure!
The method failed; David's not in the database:
Error! (Exception?) Here's stdout:
RuntimeError: Random failure!
	from (irb):14:in `create_from_new_author'
	from /usr/lib/ruby/gems/1.8/gems/activerecord-1.14.0/lib/active_record/connection_adapters/abstract/database_statements.rb:51:in `transaction'
	from /usr/lib/ruby/gems/1.8/gems/activerecord-1.14.0/lib/active_record/transactions.rb:91:in `transaction'
	from (irb):12:in `create_from_new_author'
	from (irb):22
User.find(:first, :conditions=>"name='David'")
nil nil