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">]>