class Log < ApplicationRecord belongs_to :recipe belongs_to :source_recipe, class_name: 'Recipe' belongs_to :user validates :date, presence: true validates :user_id, presence: true validates :rating, numericality: { only_integer: true, allow_blank: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 5, message: 'must be an integer between 1 and 5, inclusive' } scope :for_user, ->(user) { where(user_id: user) } scope :for_recipe, ->(recipe) { where(source_recipe_id: recipe) } accepts_nested_attributes_for :recipe, update_only: true, allow_destroy: false after_save :update_rating def update_rating if self.source_recipe self.source_recipe.update_rating! end end end