如何在Rails中更新并保存另一个模型?

在我的计划中,我有一个模型,卡路里,它取一个人吃的东西,并给他们一点点。 在针对每天的营养信息计算该点值之后,我想更新用户模型中的“点”变量。

我在卡路里模型中的代码是

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

在用户模型中,我有

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

我已经通过创建一个回调before_save测试了point_calculation模型,并且它在那里工作正常。 但是,在每次新卡路里条目之后更新更有意义,而不是用户更新其设置。 任何建议? 我错过了什么?

谢谢你的帮助。

我假设你的卡路里模型与用户有一个has_one关系,而用户has_many卡路里。

在卡路里模型:

 after_save :update_user_points def update_user_points self.user.update_calorie_points! end 

在用户模型中:

 def update_calorie_points! self.update_column(:points, self.calories.sum(:points)) end