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

Asked

Viewed 144 times

2

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

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

Only when I want to edit a cost it must always create a new record on the Tab of Custo_Historico. Does anyone have any tips?

  • Can you show which attributes of the two classes? and which ones will you replicate in the history?

  • Another thing if you’re using "_" to separate compound class names, the ideal is that you don’t. That is Custo_Historico could be called CustoHistorico following some code Lines guide.

2 answers

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.

  • Thanks Roben, But I believe there’s some other way to do it in the controller.

  • It is also possible, but it will have to be in the cost update method. When calling in the controller, you run the INSERT in Historico_custo. But you will have to check if UPDATE has run successfully, otherwise the history will not be valid.

0


One of the ways to do this type of operation is by using Callbacks and whenever a custo is saved, it will generate a new record of custo_historico.

Whereas 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 its cost becomes 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">]>
  • Thank you very much for your help!

  • @Joãohenriquesoares for nothing, needing we are there. Thank you for the vote.

Browser other questions tagged

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