1
0

Fixed formula validation during import of defaults

Previously it did not consider in-memory records and failed sometimes
This commit is contained in:
cryptogopher 2020-05-11 22:38:27 +02:00
parent ffb87a09c4
commit 7584c650da
3 changed files with 16 additions and 10 deletions

View File

@ -32,23 +32,21 @@ class BodyTrackersController < ApplicationController
attrs = q.attributes.except('id', 'project_id', 'parent_id', 'lft', 'rgt',
'created_at', 'updated_at')
if q.parent
attrs['parent_id'] = available_quantities[[q.parent.name, q.parent.domain]].id
attrs['parent'] = available_quantities[[q.parent.name, q.parent.domain]]
end
if q.formula
attrs['formula_attributes'] = q.formula.attributes
.except('id', 'quantity_id', 'unit_id', 'created_at', 'updated_at')
attrs['formula_attributes']['unit_id'] = available_units[q.formula.unit.shortname]
end
obj = @project.quantities.create(attrs)
if obj.persisted?
available_quantities[[q.name, q.domain]] = obj
else
failed_objects << obj
end
available_quantities[[q.name, q.domain]] = @project.quantities.build(attrs)
end
end
Quantity.transaction do
failed_objects += available_quantities.values.reject { |o| o.persisted? || o.save }
end
new_quantities_count = available_quantities.length - quantities_count
new_quantities_count = @project.quantities(true).size - quantities_count
flash[:notice] += ", #{new_quantities_count > 0 ? new_quantities_count : "no" } new" \
" #{'quantity'.pluralize(new_quantities_count)}"

View File

@ -58,7 +58,15 @@ class Formula < ActiveRecord::Base
identifiers, parts = parser.parse
errors = parser.errors
quantities = Quantity.where(project: self.quantity.project, name: identifiers.to_a)
project = self.quantity.project
quantities =
if project
# This is required to properly validate with in-memory records, e.g.
# during import of defaults
project.quantities.select { |q| identifiers.include?(q.name) }
else
Quantity.where(project: nil, name: identifiers.to_a)
end
identifiers -= quantities.map(&:name)
models = identifiers.map(&:safe_constantize).compact || []
(identifiers - models.map(&:class_name)).each do |i|

View File

@ -1,7 +1,7 @@
module BodyTracking::ProjectPatch
Project.class_eval do
has_many :sources, dependent: :destroy
has_many :quantities, -> { order "lft" }, dependent: :destroy
has_many :quantities, -> { order "lft" }, inverse_of: :project, dependent: :destroy
has_many :units, dependent: :destroy
has_many :foods, -> { order "foods.name" }, dependent: :destroy,