0
我在我的ruby應用程序(jurnal和jurnal_my)中有2個模型,我需要從mysql導入數據jurnal到postgresql。從mysql導入數據到postgresql
這是我的方法:
jurnal_my.rb
establish_connection "mysql"
self.table_name = "jurnal"
def self.import_from_mysql
JurnalMy.all.each{|jurnal|
hash = {}
JurnalMy.first.attributes.delete_if{|attr|%w(ID CREATED_AT UPDATED_AT).include?(attr)}.map{|case_attr|case_attr}.each{|hash_attr|
hash = hash.merge(hash_attr[0].downcase => hash_attr[1])
}
Jurnal.create hash
}
end
的database.yml
default: &default
adapter: postgresql
encoding: unicode
username: adit
password: xxxxxxx
pool: 5
development:
<<: *default
database: portalpos_development
mysql:
adapter: mysql2
encoding: utf8
username: root
password: xxxxxxx
database: app
test:
<<: *default
database: portalpos_test
當我嘗試將數據導入到PostgreSQL,它的工作。但結果是錯誤的。 數據jurnal在MySQL:
J01
J02
J03
數據在PostgreSQL的(結果)jurnal:
J01
J01
J01
你能幫助我嗎?
我試試你的方法。是工作。但是如果我有5個數據並導入兩次。如何保護postgres免受重複數據? – Sakti
也許你可以爲此使用[first_or_create](http://apidock.com/rails/ActiveRecord/Relation/first_or_create)。它會成爲'Jurnal.where(哈希).first_or_create' –
哦,上帝,再次工作。非常感謝你\ m / – Sakti