1
0

Added Target create action

This commit is contained in:
cryptogopher
2020-07-25 16:28:55 +02:00
parent 5b83860ed7
commit ffcc9553d5
12 changed files with 154 additions and 66 deletions

View File

@@ -31,7 +31,7 @@ class MeasurementsController < ApplicationController
# Nested attributes cannot create outer object (Measurement) and at the same time edit
# existing nested object (MeasurementRoutine) if it's not associated with outer object
# https://stackoverflow.com/questions/6346134/
# That's why routine needs to be found and associated before measurement initialization
# That's why Routine needs to be found and associated before Measurement initialization
@measurement = @project.measurements.new
update_routine_from_params
@measurement.attributes = measurement_params
@@ -127,7 +127,8 @@ class MeasurementsController < ApplicationController
def update_routine_from_params
routine_id = params[:measurement][:routine_attributes][:id]
@measurement.routine = @project.measurement_routines.find_by(id: routine_id) if routine_id
return unless routine_id
@measurement.routine = @project.measurement_routines.find_by(id: routine_id)
end
def prepare_items

View File

@@ -5,19 +5,59 @@ class TargetsController < ApplicationController
include Concerns::Finders
before_action :find_project_by_project_id, only: [:index, :new]
before_action :find_project_by_project_id, only: [:index, :new, :create]
def index
prepare_targets
end
def new
@target = (@goal || @project.goals.binding).targets.new
@target.arity.times { @target.thresholds.new }
target = (@goal || @project.goals.binding).targets.new
target.arity.times { target.thresholds.new }
@targets = [target]
end
def create
goal = @project.goals.find_by(id: params[:goal][:id]) || @project.goals.build(goal_params)
@targets = goal.targets.build(targets_params[:targets]) do |target|
target.effective_from = params[:target][:effective_from]
end
# :save only after build, to re-display values in case records are invalid
if goal.save && Target.transaction { @targets.all?(&:save) }
flash[:notice] = 'Created new target(s)'
prepare_targets
else
@targets.each do |target|
(target.thresholds.length...target.arity).each { target.thresholds.new }
target.thresholds[target.arity..-1].map(&:destroy)
end
render :new
end
end
private
def goal_params
params.require(:goal).permit(:id, :name, :description)
end
def targets_params
params.require(:target).permit(
targets: [
:id,
:condition,
:scope,
thresholds_attributes: [
:id,
:quantity_id,
:value,
:unit_id
]
]
)
end
def prepare_targets
@targets = @project.targets.includes(:item, :thresholds)
end