diff options
Diffstat (limited to 'app/models/target.rb')
-rw-r--r-- | app/models/target.rb | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/app/models/target.rb b/app/models/target.rb new file mode 100644 index 0000000..3063b42 --- /dev/null +++ b/app/models/target.rb @@ -0,0 +1,42 @@ +# 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.reject(&:marked_for_destruction?).sum { |a| a.percentage.to_f } + errors.add(:base, "La somme des pourcentages doit être égale à 100%") unless (sum - 100.0).abs <= 0.01 + end +end |