1
0

Added Ingredient/Nutrient initialization

This commit is contained in:
cryptogopher 2019-09-15 19:55:25 +02:00
parent 9878b42655
commit 6e3cf2f189
3 changed files with 17 additions and 2 deletions

View File

@ -4,8 +4,9 @@ class IngredientsController < ApplicationController
before_action :authorize before_action :authorize
def index def index
@ingredient = Ingredient.new @ingredient = Ingredient.new(project: @project)
@ingredient.nutrients.build # passing attr for after_initialize
@ingredient.nutrients.new(ingredient: @ingredient)
@ingredients = @project.ingredients @ingredients = @project.ingredients
end end

View File

@ -24,4 +24,12 @@ class Ingredient < ActiveRecord::Base
validates :ref_amount, numericality: {greater_than: 0} validates :ref_amount, numericality: {greater_than: 0}
validates :ref_unit, presence: true, associated: true validates :ref_unit, presence: true, associated: true
validates :group, inclusion: {in: groups.keys} validates :group, inclusion: {in: groups.keys}
after_initialize do
if new_record?
units = self.project.units
self.ref_unit ||= units.find_by(shortname: 'g') || units.first
end
end
end end

View File

@ -8,4 +8,10 @@ class Nutrient < ActiveRecord::Base
validates :quantity, presence: true, associated: true, uniqueness: {scope: :ingredient_id} validates :quantity, presence: true, associated: true, uniqueness: {scope: :ingredient_id}
validates :amount, numericality: {greater_than: 0} validates :amount, numericality: {greater_than: 0}
validates :unit, presence: true, associated: true validates :unit, presence: true, associated: true
after_initialize do
if new_record?
self.unit ||= self.ingredient.ref_unit
end
end
end end