Monday, April 07, 2008

ActiveRecord::Base transaction explain


#---
# Excerpted from "Agile Web Development with Rails, 2nd Ed.",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/rails2 for more book information.
#---
# $: << File.dirname(__FILE__)

require "logger"
require "rubygems"
require "active_record"

ActiveRecord::Base.logger = Logger.new(STDOUT)

ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:user => "root",
:password => "",
:database => "test"
)

# InnoDB table: users, accounts
ActiveRecord::Schema.define do

create_table :accounts, :force => true do |t|
t.column :number, :string
t.column :balance, :decimal, :precision => 10, :scale => 2, :default => 0
end

create_table :users, :force => true do |t|
t.column :name, :string
t.column :password, :string
end

end

class User < ActiveRecord::Base
end

class Account < ActiveRecord::Base
end

Account.transaction do
Account.create(:balance => 100, :number => "12345")
User.create(:name => 'test', :password => "123456")
raise 'error!!!'
# 如果transaction内部所有SQL都正确执行并且通过ActiveRecord::Base validates,在block中没有raise的话则正确写入数据库
# 如果有SQL错误或者validates没有通过,或者是transaction中有raise错误,则事务会ROLLBACK
# ROLLBACK 是基于事务表(如InnoDB表)的,非事务表(如MyISAM表)则需要在程序中手工回滚
end

No comments :