From 8240e5e8684ae2612f53b0890fa797655927b62e Mon Sep 17 00:00:00 2001 From: cryptogopher Date: Sun, 21 Jun 2020 02:48:32 +0200 Subject: [PATCH] Added Target and Threshold models --- app/models/target.rb | 14 ++++++++++++++ app/models/threshold.rb | 6 ++++++ db/migrate/001_create_schema.rb | 2 +- 3 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 app/models/target.rb create mode 100644 app/models/threshold.rb diff --git a/app/models/target.rb b/app/models/target.rb new file mode 100644 index 0000000..96d273f --- /dev/null +++ b/app/models/target.rb @@ -0,0 +1,14 @@ +class Target < ActiveRecord::Base + belongs_to :goal, inverse_of: :targets + belongs_to :item, polymorphic: true, inverse_of: :targets + has_many :thresholds, as: :registry, inverse_of: :target, dependent: :destroy, + validate: true + + 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: [:<, :<=, :>, :>=, :==]} + validates :scope, inclusion: {in: [:day], if: -> { thresholds.first.domain == :diet }} + validates :effective_from, presence: {unless: goal?}, absence: {if: goal?} +end diff --git a/app/models/threshold.rb b/app/models/threshold.rb new file mode 100644 index 0000000..54f6ad1 --- /dev/null +++ b/app/models/threshold.rb @@ -0,0 +1,6 @@ +class Threshold < QuantityValue + belongs_to :target, foreign_key: 'registry_id', foreign_type: 'foreign_type', + inverse_of: :thresholds, polymorphic: true, required: true + + validates :value, numericality: true +end diff --git a/db/migrate/001_create_schema.rb b/db/migrate/001_create_schema.rb index 19c6a2b..170492f 100644 --- a/db/migrate/001_create_schema.rb +++ b/db/migrate/001_create_schema.rb @@ -95,7 +95,7 @@ class CreateSchema < ActiveRecord::Migration create_table :targets do |t| t.references :goal - t.references :threshold + t.references :item, polymorphic: true t.string :condition t.string :scope t.date :effective_from