# app/models/consolidacao_motorista.rb class ConsolidacaoMotorista < ApplicationRecord belongs_to :consolidacao has_many :consolidacao_entregas, ->(cm) { where(motorista_nome: cm.motorista_nome) }, foreign_key: :consolidacao_id, primary_key: :consolidacao_id validates :motorista_nome, presence: true validates :motorista_nome, uniqueness: { scope: :consolidacao_id } before_save :recalcular_valor def recalcular_valor cfg = Configuracao self.valor_total = consolidacao_entregas .includes(:consolidacao) .where(motorista_nome: motorista_nome) .sum do |e| case e.tipo when 'entrega_normal' then cfg.preco_entrega when 'retirada' then cfg.preco_retirada when 'bonus' then cfg.preco_bonus when 'desconto' then -cfg.preco_desconto else 0 end end end end