多数据库的访问
目的:在同一个应用中访问不同数据库,以在同一controller的同一action中访问不同数据库为例
准备:
两个已经建立好的数据库
数据库一:db1,包含表bikes(字段为id,name)
数据库二:db2,包含表cars(字段为id,name)
database.yml文件添加如下内容
db1: adapter: mysql encoding: utf8 reconnect: false database: db1 pool: 5 username: root password: 123456 host: localhost db2: adapter: mysql encoding: utf8 reconnect: false database: db2 pool: 5 username: root password: 123456 host: localhost
model如下
class Db1 < ActiveRecord::Base establish_connection :db1 self.abstract_class = true end class Bike < Db1 end class Db2 < ActiveRecord::Base establish_connection :db2 self.abstract_class = true end class Car < Db2 end
即,为每个数据库建立一个继承自ActiveRecord::Base的类。在此数据库中的表所对应的模型则继承自相应的数据库类
测试代码如下:
D:\myruby\study\demo>ruby script/console Loading development environment (Rails 2.3.8) >> b = Bike.create({:name=>"bike"}) => #<Bike id: 2, name: "bike"> >> Bike.find 2 => #<Bike id: 2, name: "bike"> >> c = Car.create({:name=>"car"}) => #<Car id: 2, name: "car"> >> Car.find 2 => #<Car id: 2, name: "car">
数据库的事务
官方文档:http://api.rubyonrails.org/classes/ActiveRecord/Transactions.html
单个数据库的事务
代码如下
Bike.delete_all Bike.transaction do Bike.create({:name=>"bike1"}) Bike.create({:name=>"bike2"}) raise ActiveRecord::Rollback #抛出异常,此异常仅仅让事务回滚 end bikes = Bike.find :all @size = bikes.size
在页面显示 @size的值为 0
多个数据库的事务
代码如下:
Bike.delete_all Car.delete_all begin Bike.transaction do Car.transaction do Bike.create({:name=>"bike"}) Car.create({:name=>"car"}) raise "test" #抛出异常 end end rescue =>ex logger.debug "ex" end bikes = Bike.find :all cars = Car.find :all @size_b = bikes.size @size_c = cars.size
页面显示 0 0,即回滚成功
奇怪,在公司里面怎么对两个数据库操作就是死活回滚不了,而在家里却可以。