diff --git a/app/controllers/ingredients_controller.rb b/app/controllers/ingredients_controller.rb index 76efd38..ab0cd0d 100644 --- a/app/controllers/ingredients_controller.rb +++ b/app/controllers/ingredients_controller.rb @@ -4,8 +4,9 @@ class IngredientsController < ApplicationController before_action :authorize def index - @ingredient = Ingredient.new - @ingredient.nutrients.build + @ingredient = Ingredient.new(project: @project) + # passing attr for after_initialize + @ingredient.nutrients.new(ingredient: @ingredient) @ingredients = @project.ingredients end diff --git a/app/models/ingredient.rb b/app/models/ingredient.rb index a163d99..d79ea5c 100644 --- a/app/models/ingredient.rb +++ b/app/models/ingredient.rb @@ -24,4 +24,12 @@ class Ingredient < ActiveRecord::Base validates :ref_amount, numericality: {greater_than: 0} validates :ref_unit, presence: true, associated: true 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 diff --git a/app/models/nutrient.rb b/app/models/nutrient.rb index e8275b3..df60400 100644 --- a/app/models/nutrient.rb +++ b/app/models/nutrient.rb @@ -8,4 +8,10 @@ class Nutrient < ActiveRecord::Base validates :quantity, presence: true, associated: true, uniqueness: {scope: :ingredient_id} validates :amount, numericality: {greater_than: 0} validates :unit, presence: true, associated: true + + after_initialize do + if new_record? + self.unit ||= self.ingredient.ref_unit + end + end end