How to do a data migration routine?

0

Suppose I have one registration model and one user model. How do I get each registration record sent to the users? This should also be done with each new record that is created in the registry, it must be migrated to the user model.

I'm new to Rails, I do not have much knowledge of Active Record.

    
asked by anonymous 28.12.2016 / 19:31

1 answer

0

To create this automatic "migration" you must use one of the callbacks provided by Active Record (AR) within your Model. The choice depends on the logic of your business. RA provides several triggers or times of entry. See the link below:

link

The code below does what you want.

  

... should be done with each new record that is created in the registry ...

The user-type object will be created shortly after the creation of the Master object using the after_create: call_for_user

Remember: the copy_to_user method will run automatically if the record object is created. That is, if the object of type User is not created then an object of type Cadastre will not be created by the method copy_for_user .

But be careful, the code below does not guarantee user creation. For this, you must enclose the entire operation (creation of user registration and creation) in a transaction , but this is outside the scope of the question.

# carregando bibliotecas
require 'sqlite3'
require "active_record"

# Conectando ao sqlite3
# Obs: rodando banco na memória ao invés de gravar em arquivo;
# o banco desaparece ao final da execução
ActiveRecord::Base.establish_connection(
    adapter: 'sqlite3',
    database: ':memory:'
)

# detalhes do esquema do banco
ActiveRecord::Schema.define do
  create_table :cadastros do |t| # o nome da tabela deve estar no plural
    t.string :nome
    t.string :sobrenome
    t.string :email
  end

  create_table :usuarios do |t| # o nome da tabela deve estar no plural
    t.string :nome_completo
    t.string :email
  end
end

# Model Cadastro
class Cadastro < ActiveRecord::Base

  # Método que deve ser executado automaticamente(callback) 
  # depois que o objeto é criado(after_create)
  after_create :copia_para_usuario

  # Implementação
  def copia_para_usuario
    usuario = Usuario.new
    # Concatenando nome e sobrenome
    usuario.nome_completo = self.nome + ' ' + self.sobrenome
    usuario.email = self.email
    usuario.save
  end
end

# Model Usuário
class Usuario < ActiveRecord::Base

end

# Criando dois objetos do tipo Cadastro
cadastro1 = Cadastro.create!(nome: 'Bento', sobrenome: 'Carneiro',
                             email:'[email protected]' )
cadastro2 = Cadastro.create!(nome: 'Conde', sobrenome: 'Dracula', 
                             email:'[email protected]' )

# Listando todos os cadastros
puts Cadastro.pluck(:id, :nome, :sobrenome, :email)

puts '-'*10 # separador

# Listando usuarios que foram "migrados" automaticamente
puts Usuario.pluck(:id, :nome_completo, :email)

Script Output:

-- create_table(:cadastros)
-> 0.0605s
-- create_table(:usuarios)
-> 0.0009s
1
Bento
Carneiro
[email protected]
2
Conde
Dracula
[email protected]
----------
1
Bento Carneiro
[email protected]
2
Conde Dracula
[email protected]
    
02.01.2017 / 15:26