3

In my program, I have a model, Calorie, that takes what a person ate and gives them a point total. After that point value is calculated for each day's nutritional information, I want to update the 'points' variable in the User model.

The code I have in the Calorie model is

before_save :calculate_points

def calculate_points
    # snipped calculations
    User.where(user_id).first.point_calculation
end

In the User model, I have

def point_calculation
    self.points = Calorie.where(user_id: id).sum(:points)
end

I've tested the point_calculation model by creating a callback before_save, and it works fine there. But it makes a lot more sense to update after each new Calorie entry, instead of a user updating their settings. Any advice? What am I missing?

Thanks for your help.

Coco13
  • 43
  • 5

1 Answers1

3

I'm assuming your Calorie model has a has_one relationship with the User, and User has_many Calories.

In Calorie model:

after_save :update_user_points

def update_user_points
    self.user.update_calorie_points!
end

In User model:

def update_calorie_points!
    self.update_column(:points, self.calories.sum(:points))
end
nomatteus
  • 502
  • 4
  • 6