How can I update and save one model from another in Rails?

后端 未结 1 1670
[愿得一人]
[愿得一人] 2021-01-21 07:38

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,

1条回答
  •  一生所求
    2021-01-21 08:15

    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
    

    0 讨论(0)
提交回复
热议问题