1
0

Preliminary Target #new support

This commit is contained in:
cryptogopher
2020-06-27 21:52:32 +02:00
parent 1dd2e2b596
commit 0df2c6ec4f
18 changed files with 177 additions and 26 deletions

View File

@@ -1,5 +1,7 @@
class Target < ActiveRecord::Base
belongs_to :goal, inverse_of: :targets
CONDITIONS = [:<, :<=, :>, :>=, :==]
belongs_to :goal, inverse_of: :targets, required: true
belongs_to :item, polymorphic: true, inverse_of: :targets
has_many :thresholds, as: :registry, inverse_of: :target, dependent: :destroy,
validate: true
@@ -7,19 +9,25 @@ class Target < ActiveRecord::Base
validates :thresholds, presence: true
accepts_nested_attributes_for :thresholds, allow_destroy: true,
reject_if: proc { |attrs| attrs['quantity_id'].blank? && attrs['value'].blank? }
# TODO: validate thresholds count according to condition type
validates :condition, inclusion: {in: [:<, :<=, :>, :>=, :==]}
validate do
errors.add(:thresholds, :count_mismatch) unless thresholds.count == arity
errors.add(:thresholds, :quantity_mismatch) if thresholds.to_a.uniq(&:quantity) != 1
end
validates :condition, inclusion: {in: CONDITIONS }
validates :scope, inclusion: {in: [:day], if: -> { thresholds.first.domain == :diet }}
validates :effective_from, presence: {unless: -> { goal.present? }},
absence: {if: -> { goal.present? }}
validates :effective_from, presence: {unless: :is_binding?}, absence: {if: :is_binding?}
after_initialize do
if new_record?
self.condition = :<
self.condition = CONDITIONS.first
end
end
def arity
BigDecimal.method(condition).arity
end
def is_binding?
goal == goal.project.goals.binding
end
end