ActiveRecord 是好東西,可以簡化很多代碼,在 Rails 之外做資料維護時也是超級好用。今天需要在兩個資料庫之間做下資料遷移,因為 schema 有變,是以 mysqldump 基本沒什麼用。
先是發現了一個 ar_fixture 的插件,使用方法極度簡單,但是出現了 UTF-8 不支援的問題,我資料庫裡使用中文的字段竟然按照 binary 處理,不了解。
最終找到一篇文章 很靠譜,實驗一下,問題搞定。
先寫一個資料庫配置檔案 database.yml
db1:
adapter: mysql
host: localhost
username: root
password:
database: database1
db2:
adapter: mysql
host: mysql
username: root
password:
database: database2
然後寫一個 imgration.rb
require ‘rubygems’
require ‘active_record’
require ‘yaml’
$config = YAML.load_file(File.join(File.dirname(__FILE__), ‘database.yml’))
class Database1 < ActiveRecord::Base
establish_connection $config['db1']
end
class Database2 < ActiveRecord::Base
establish_connection $config['db2']
end
module A
class Tb1 < Database1
set_table_name 'tablename1'
end
end
module B
class Tb2 < Database2
set_table_name 'tablename2'
end
end
... your task process ..
把兩個資料庫分别寫在兩個 module 裡面,好處是可以避免命名空間沖突, 壞處是代碼多了一點,調用時應該:
tb1 = A::Tb1.find :all
tb2 = B::Tb2.find :all