I would like to calculate the values of a specific field in my table item_compras
create_table "item_compras", force: :cascade do |t|
t.integer "cantidad_bidon"
t.integer "total_bidones"
end
I am using accepts_nested_attributes_for :item_compras
, in the model Compra
, so in the shopping form I can enter more than one item_compra
.
Suppose I enter a item_compra
that has 5
in cantidad_bidon
and another has 4
, which as a result should be saved in the field total_bidones
giving a total of 9
drums, but if only entry a item_compra
, the item must be saved without performing any operation. Can I do this with a after_create
?
EDITING
I'm using after_create :total_bidones_compra
in model ItemCompra
def total_bidones_compra
suma = self.cantidad_bidon + self.cantidad_bidon
self.total_bidones = suma
self.save
end
In this way I would only be making the sum of only 2
items, but if I enter more than this amount, it does not keep adding up.
In the Compras
controller, I simply add the model attributes ItemCompra
def compra_params
params.require(:compra).permit(...,
item_compras_attributes: [:id, :cantidad_bidon, :product_id, :calibre_id, :kg_bidon, :precio_kg, :_destroy ])
end
EDIT N ° 2
Action of ComprasController
def new
@compra = Compra.new
5.times { @compra.item_compras.build }
end
def create
@compra = Compra.new(compra_params)
respond_to do |format|
if @compra.save
format.html { redirect_to @compra, notice: 'La compra ha sido creada exitosamente.' }
format.json { render :show, status: :created, location: @compra }
else
format.html { render :new }
format.json { render json: @compra.errors, status: :unprocessable_entity }
end
end
end