View raw

1 class TargetsController < ApplicationController 2 before_action :set_target, only: %i[show edit update destroy] 3 4 def index 5 @targets = Target.order(:name) 6 end 7 8 def new 9 @target = Target.new 10 @nutrient_profiles = NutrientProfile.order(:name) 11 # Build one allocation per profile so each appears as a row 12 @nutrient_profiles.each do |np| 13 @target.target_allocations.build(nutrient_profile: np, percentage: 12.5) 14 end 15 end 16 17 def create 18 @target = Target.new(target_params) 19 if @target.save 20 redirect_to @target, notice: "Cible créée." 21 else 22 # Rebuild rows for any profiles missing (e.g., after validation errors) 23 existing_ids = @target.target_allocations.map(&:nutrient_profile_id) 24 (NutrientProfile.where.not(id: existing_ids)).order(:name).each do |np| 25 @target.target_allocations.build(nutrient_profile: np, percentage: 0) 26 end 27 render :new, status: :unprocessable_entity 28 end 29 end 30 31 def edit 32 end 33 34 def update 35 if @target.update(target_params) 36 redirect_to @target, notice: "Cible mise à jour." 37 else 38 render :edit, status: :unprocessable_entity 39 end 40 end 41 42 def destroy 43 @target = Target.find(params[:id]) 44 @target.destroy 45 respond_to do |format| 46 format.turbo_stream { render turbo_stream: turbo_stream.remove(dom_id(@target)) } 47 format.html { redirect_to targets_path, notice: "Cible supprimé." } 48 end 49 end 50 51 private 52 53 def set_target 54 @target = Target.find(params[:id]) 55 end 56 57 def target_params 58 params.require(:target).permit( 59 :name, 60 target_allocations_attributes: [ :id, :nutrient_profile_id, :percentage, :_destroy ] 61 ) 62 end 63 end 64