How to edit and create new record in DB? Ruby on rails

2

I would like to know how I can do the following situation.

I have 2 templates Custo and Custo_Historico all CRUD is already working.

But when I want to edit a cost it should always create a new record in the Custo_Historico Tab. Anyone have any tips?

    
asked by anonymous 23.06.2016 / 20:27

2 answers

0

One way to do this is to use Callbacks and whenever a custo is saved, it will generate a new record of custo_historico .

Since you have implemented a 1xN relationship between Custo and CustoHistórico ( has_many / belongs_to ) and Custo has an attribute called value, we can use callback as follows:

class Custo < ActiveRecord::Base
  has_many :custo_historicos
  after_save :gravar_historico

  def gravar_historico
    custo_historicos.create(valor: valor)
  end
end

class CustoHistorico < ActiveRecord::Base
  belongs_to :custo
end

Then the history of your cost, it stays automatic:

c = Custo.create(valor: 1.0)
c.custo_historicos
=> #<ActiveRecord::Associations::CollectionProxy [#<CustoHistorico id: 1, valor: #<BigDecimal:68a13e8,'0.1E1',9(27)>, custo_id: 1, created_at: "2016-06-24 11:59:21", updated_at: "2016-06-24 11:59:21">]>


c.update(valor: 2)
c.custo_historicos
=> #<ActiveRecord::Associations::CollectionProxy [#<CustoHistorico id: 1, valor: #<BigDecimal:68a13e8,'0.1E1',9(27)>, custo_id: 1, created_at: "2016-06-24 11:59:21", updated_at: "2016-06-24 11:59:21">, #<CustoHistorico id: 2, valor: #<BigDecimal:68e6790,'0.2E1',9(27)>, custo_id: 1, created_at: "2016-06-24 12:00:14", updated_at: "2016-06-24 12:00:14">]>
    
24.06.2016 / 13:28
1

Create a database TRIGGER in the cost table, which will be responsible for storing in Custo_Historico the history of the changes made.

CREATE OR REPLACE TRIGGER MON_ALT_CUSTO ON UPDATE custo
FOR REACH ROW
BEGIN
   //... Código para inserir os dados na tabela histórico.
END;

This would be the simplest form. The creation syntax can vary depending on the DBMS you are using.

    
23.06.2016 / 22:13