Finished Ingredient#create validations
This commit is contained in:
@@ -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}
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user