I would like to know how I can calculate the "used" and "quantity" values of two models that I generated earlier called bidon and control .
This is the schema
create_table "bidons", force: :cascade do |t|
t.integer "usado"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "control", force: :cascade do |t|
t.integer "bidon_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "cantidad"
end
In the bidon model I have the following:
class Bidon < ActiveRecord::Base #bank
has_many :controls, dependent: :destroy
accepts_nested_attributes_for :controls
validates :name, presence: true
def to_s
name
end
end
Here I use accepts_nested_attributes_for to edit the current amount of drums from the bidon model. (With this I have no problems).
In the control model I have:
class Control < ActiveRecord::Base #bank_subsidiaries
belongs_to :bidon
validates :cantidad, presence: true
def to_s
cantidad
end
end
What I would like to do is calculate the values: used and quantity in the case of creating or editing a drum, the idea is that the amount of control is modified.
Do I have to do it from the Bidon driver in this case?
In the controller of the drums that I have to set so that these values are calculated?
def create
#@bidon = Bidon.new(bidon_params)
@bidon = Bidon.new(bidon_params)
respond_to do |format|
if @bidon.save
format.html { redirect_to @bidon, notice: 'Bidon was successfully created.' }
format.json { render :show, status: :created, location: @bidon }
else
format.html { render :new }
format.json { render json: @bidon.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /bidons/1
# PATCH/PUT /bidons/1.json
def update
respond_to do |format|
if @bidon.update(bidon_params)
format.html { redirect_to @bidon, notice: 'Bidon was successfully updated.' }
format.json { render :show, status: :ok, location: @bidon }
else
format.html { render :edit }
format.json { render json: @bidon.errors, status: :unprocessable_entity }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_bidon
@bidon = Bidon.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def bidon_params
params.require(:bidon).permit(:name, :usado, controls_attributes: [:id, :cantidad])
end
end
My form shows me the amount available in the control , so now when entering the amount used, suppose I want to add it, there should be a total reflected in the total amount of the control nothing else.
Thank you very much!