From 37e3b98788985e7f0092b21df7e101df6bd42896 Mon Sep 17 00:00:00 2001 From: cryptogopher Date: Tue, 20 Apr 2021 16:57:15 +0200 Subject: [PATCH] Improve #create action --- app/controllers/targets_controller.rb | 11 +++++++++-- app/models/goal.rb | 6 +++++- app/views/targets/_form.html.erb | 3 +-- config/locales/en.yml | 5 +++++ 4 files changed, 20 insertions(+), 5 deletions(-) diff --git a/app/controllers/targets_controller.rb b/app/controllers/targets_controller.rb index ebf2fe3..f170c46 100644 --- a/app/controllers/targets_controller.rb +++ b/app/controllers/targets_controller.rb @@ -28,8 +28,15 @@ class TargetsController < ApplicationController params[:goal][:targets_attributes].each { |ta| ta[:effective_from] = @effective_from } if @goal.update(targets_params) - flash.now[:notice] = 'Created new target(s)' - prepare_targets + count = @goal.targets.target.length + if count > 0 + flash.now[:notice] = t('.success', count: count) + prepare_targets + else + flash.now[:warning] = t('.success', count: 0) + @targets = [@goal.targets.new] + render :new + end else @targets = @goal.targets.select(&:changed_for_autosave?) @targets.each { |t| t.thresholds.new unless t.thresholds.present? } diff --git a/app/models/goal.rb b/app/models/goal.rb index 2cba479..388daa9 100644 --- a/app/models/goal.rb +++ b/app/models/goal.rb @@ -6,7 +6,11 @@ class Goal < ActiveRecord::Base class_name: 'Exposure', extend: BodyTracking::TogglableExposures has_many :quantities, -> { order "lft" }, through: :exposures - accepts_nested_attributes_for :targets, allow_destroy: true + accepts_nested_attributes_for :targets, allow_destroy: true, + reject_if: proc { |attrs| + attrs[:quantity_id].blank? && + attrs[:thresholds_attributes].all? { |t| t[:value].blank? } + } include Validations::NestedUniqueness validates_nested_uniqueness_for :targets, :effective_from, :quantity_id, :item_type, :item_id, :scope, diff --git a/app/views/targets/_form.html.erb b/app/views/targets/_form.html.erb index 30f2d79..53432ce 100644 --- a/app/views/targets/_form.html.erb +++ b/app/views/targets/_form.html.erb @@ -42,8 +42,7 @@ var row = form.find('p.target:visible:last'); var new_row = row.clone().insertAfter(row); new_row.find('em').text('<%= t ".choose_quantity" %>'); - new_row.find('input, select').val(''); - new_row.find('select[id$=__unit_id]').val(row.find('select[id$=__unit_id]').val()); + new_row.find('input, select:first').val(''); new_row.find('label:first').hide(); form.find('p.target:visible a.icon-del').show(); } diff --git a/config/locales/en.yml b/config/locales/en.yml index ffb655e..eeaac3c 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -117,6 +117,11 @@ en: heading: 'Targets' show: label_target: 'Target' + create: + success: + zero: "No targets specified" + one: "Created 1 target" + other: "Created %{count} targets" meals: contextual: link_new_meal: 'New meal'