每天一剂Rails良药之Connecting to Multiple Databases

预备知识:
1,Rails启动后没有马上建立数据库连接,而是当model第一次调用connect()方法时建立连接
2,默认情况下ActiveRecord::Base建立数据库连接,然后它的所有子类即所有的model均拥有该连接
3,model查找数据库连接时从自己开始向它的父一层一层查找连接,直到找到为止

如果我们的Rails应用需要建立对多个数据库的连接,我们该怎样做呢?

1,database.yml
[code]
development:
adapter: mysql
database: default
username: root
password:
socket: /tmp/mysql.sock

products:
adapter: mysql
database: products
username: root
password:
socket: /tmp/mysql.sock
[/code]
这里我们的Rails系统默认使用default这个数据库,products作为外部数据库待使用。

2,product.rb
[code]
class Product < ActiveRecord::Base
establish_connection :products
end
[/code]
假设products数据库有一个products表,我们用establish_connection来声明建立到哪个数据库的连接即可

3,add_product_reference_table.rb和product_reference.rb
[code]
class AddProductReferenceTable < ActiveRecord::Migration
def self.up
create_table :product_references do |t|
t.column :product_id, :integer
end
end
def self.down
drop_table :product_references
end
end

class ProductReference < ActiveRecord::Base
belongs_to :product
has_and_belongs_to_many :carts,
:join_table => "carts_products",
:foreign_key => "product_id"
def name
product.name
end
def price
product.price
end
end

class Cart < ActiveRecord::Base
has_and_belongs_to_many :products,
:class_name => "ProductReference",
:join_table => "carts_products",
:association_foreign_key => "product_id"
[/code]
这样我们通过建立一个对product的reference来在我们默认的数据库里直接使用外部数据库的表,不过我们需要同步product_references表和products的id

4,使用外部数据库的多个表时
我们可以建立一个父类,然后集成它即可
[code]
class External < ActiveRecord::Base
self.table_name_prefix = "foo"
establish_connection :products
end

class Product < External
end

class TaxConversion < External
end
[/code]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值