0

I have 2 models in my ruby app (jurnal and jurnal_my) and i need to import data jurnal from mysql to postgresql.

This is my method :

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

When i try to import data to postgresql, it's working. But the result is wrong. Data jurnal in mysql :

J01
J02
J03 

Data jurnal in postgresql (result) :

J01
J01
J01

Can you help me?

1 Answer 1

1

You're calling JurnalMy.first, hence you're only creating the first record. You should call attributes on jurnal. Also better to use find_each instead of loading all the records on memory.

JurnalMy.find_each do |jurnal|
  hash = {}
  jurnal.attributes # ...
  Jurnal.create hash
end
Sign up to request clarification or add additional context in comments.

2 Comments

I have try your method. Its work. But if I have 5 datum and import for twice. How to protect the postgres from duplicate data?
Maybe you could use first_or_create for this. It'll be Jurnal.where(hash).first_or_create

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.