class TargetsController < ApplicationController before_action :set_target, only: %i[show edit update destroy] def index @targets = Target.order(:name) end def new @target = Target.new @nutrient_profiles = NutrientProfile.order(:name) # Build one allocation per profile so each appears as a row @nutrient_profiles.each do |np| @target.target_allocations.build(nutrient_profile: np, percentage: 12.5) end end def create @target = Target.new(target_params) if @target.save redirect_to @target, notice: "Cible créée." else # Rebuild rows for any profiles missing (e.g., after validation errors) existing_ids = @target.target_allocations.map(&:nutrient_profile_id) (NutrientProfile.where.not(id: existing_ids)).order(:name).each do |np| @target.target_allocations.build(nutrient_profile: np, percentage: 0) end render :new, status: :unprocessable_entity end end def edit end def update if @target.update(target_params) redirect_to @target, notice: "Cible mise à jour." else render :edit, status: :unprocessable_entity end end def destroy @target = Target.find(params[:id]) @target.destroy respond_to do |format| format.turbo_stream { render turbo_stream: turbo_stream.remove(dom_id(@target)) } format.html { redirect_to targets_path, notice: "Cible supprimé." } end end private def set_target @target = Target.find(params[:id]) end def target_params params.require(:target).permit( :name, target_allocations_attributes: [ :id, :nutrient_profile_id, :percentage, :_destroy ] ) end end