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">]>
Can you show which attributes of the two classes? and which ones will you replicate in the history?
– Luiz Carvalho
Another thing if you’re using "_" to separate compound class names, the ideal is that you don’t. That is
Custo_Historico
could be calledCustoHistorico
following some code Lines guide.– Luiz Carvalho