railsで複数DB


1.テーブル毎に切り替え

  • ユーザ認証DBだけ別サーバなんて場合に使える。

config/database.yml

development:
  adapter: mysql
  database: xxx
  username: foo
  password: bar
  host: server
  encoding: utf8

development2:
  adapter: mysql
  database: xxx
  username: foo
  password: bar
  host: server2
  encoding: utf8

app/models/user.rb

class User
  establish_connection :development2
end

2.リクエスト毎に切り替え

http://techno.hippy.jp/rorwiki/?cmd=view&p=HowtoUseMultipleDatabases&key=howtouse

  • Controllerのbefore_filterでActiveRecode::Base.establish_connectionを呼ぶ。
  • リクエストの度にコネクション取得し直しぽい。

3.DB呼び出し毎に切り替え(コネクション保持)

  • マスタ(更新系)・スレーブ(検索系)構成でも使える??
  • config/database.yamlは1と同じ

app/models/user.rb

class User
end

app/models/slave_user.rb

class SlaveUser
  set_table_name "users"
  establish_connection(:development2)
end

ruby script/console

>> User.connection.active?
=> true

>> SlaveUser.connection.active?
=> true

>> User.create
=> #<User:0xb74dd714 @errors=#<ActiveRecord::Errors:0xb74db644 @base=#<User:0xb74dd714 ...>, @errors={}>, @new_record=false, @new_record_before_save=true, @attributes={"name"=>nil, "id"=>1}>           

>> User.find(:all)
=> [#<User:0xb74d6360 @attributes={"name"=>nil, "id"=>"1"}>]

>> SlaveUser.find(:all)
=> []

>> SlaveUser.superclass.find(:all)
=> [#<User:0xb74b78e8 @attributes={"name"=>nil, "id"=>"1"}>]

関連テーブルの扱いがややこしそう。


マージンFXのひまわり証券さん、ニンテンドーDS Lite欲しい!