How to do a data migration routine?

Asked

Viewed 88 times

0

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

I’m new to Rails, I don’t have much knowledge of Active Record.

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. AR provides multiple triggers or input moments. See the link below:

http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html


The code below does what you want.

...should be made to each new record that is created in the register...

The User type object will be created right after the creation of the Register object via the trigger/callback after_create :copia_para_usuario

Remember: the method of copia_para_usuario will run automatically if the registration object is created. That is, if the User object is not created then a Registration object will not be created by the method copia_para_usuario.

But attention, the code below does not guarantee user creation. For this you must include the whole operation (creation of registration and user 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]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.