summaryrefslogtreecommitdiff
path: root/app/controllers/targets_controller.rb
blob: 679cb753d6150b989483444e78aafef10a8a292d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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
Copyright 2019--2026 Marius PETER