1
0

Finished Ingredient#create validations

This commit is contained in:
cryptogopher
2019-09-15 18:53:00 +02:00
parent 0dcb13a065
commit 893e2646d0
4 changed files with 23 additions and 9 deletions

View File

@@ -5,11 +5,19 @@ class Ingredient < ActiveRecord::Base
belongs_to :project
belongs_to :ref_unit, class_name: 'Unit'
has_many :nutrients, inverse_of: :ingredient
accepts_nested_attributes_for :nutrients, allow_destroy: true
#reject_if: proc { |attrs|
# attrs['quantity_id'].blank? && attrs['amount'].blank?
#}
accepts_nested_attributes_for :nutrients, allow_destroy: true, reject_if: proc { |attrs|
attrs['quantity_id'].blank? && attrs['amount'].blank?
}
validates_associated :nutrients
# Nutrient quantity_id uniqueness check for nested attributes
validate on: :create do
quantities = self.nutrients.map { |n| n.quantity_id }
if quantities.length != quantities.uniq.length
errors.add(:nutrients, :duplicated_quantity)
end
end
validates :project, associated: true
validates :name, presence: true, uniqueness: {scope: :project_id}

View File

@@ -3,7 +3,8 @@ class Nutrient < ActiveRecord::Base
belongs_to :quantity
belongs_to :unit
validates :ingredient, presence: true, associated: true
# disabled to avoid loop with Ingredient 'validates_associated :nutrients'
#validates :ingredient, presence: true, associated: true
validates :quantity, presence: true, associated: true, uniqueness: {scope: :ingredient_id}
validates :amount, numericality: {greater_than: 0}
validates :unit, presence: true, associated: true