1
0
This repository has been archived on 2023-12-07. You can view files and clone it, but cannot push or open issues or pull requests.
cryptogopher e78803e474 Added MealsController#new and form autocomplete for Food
Renamed QuantityColumn -> Exposure
2020-04-15 23:42:58 +02:00

20 lines
764 B
Ruby

class Meal < ActiveRecord::Base
belongs_to :project, required: true
has_many :ingredients, as: :composition, dependent: :destroy, validate: true
has_many :foods, through: :ingredients
validates :ingredients, presence: true
accepts_nested_attributes_for :ingredients, allow_destroy: true, reject_if: proc { |attrs|
attrs['food_id'].blank? && attrs['amount'].blank?
}
# Ingredient food_id + part_of_id uniqueness validation. Cannot be effectively
# checked on Ingredient model level.
validate do
ingredients = self.ingredients.reject { |i| i.marked_for_destruction? }
.map { |i| [i.food_id, i.part_of_id] }
if ingredients.length != ingredients.uniq.length
errors.add(:ingredients, :duplicated_ingredient)
end
end
end