# app/models/target.rb class Target < ApplicationRecord has_many :target_allocations, dependent: :destroy has_many :nutrient_profiles, through: :target_allocations accepts_nested_attributes_for :target_allocations, allow_destroy: true # validate :percentages_sum_to_100 def weighted_requirements totals = Hash.new(0.0) denom = 100.0 target_allocations.includes(:nutrient_profile).each do |alloc| profile = alloc.nutrient_profile next unless profile weight = (alloc.percentage || 0).to_f / denom next if weight <= 0 # Prefer the helper, but gracefully fall back to slicing attributes. reqs = if profile.respond_to?(:requirements_hash) profile.requirements_hash else profile.attributes.slice(*NutrientProfile::NUTRIENT_KEYS.map(&:to_s)) end reqs.each do |nutrient_key, value| next if value.nil? totals[nutrient_key.to_s] += value.to_f * weight end end totals end private # def percentages_sum_to_100 # sum = target_allocations.sum { |a| a.percentage.to_f } # errors.add(:base, "La somme des pourcentages doit être égale à 100%") unless (sum - 100.0).abs <= 0.1 # end end