Ruby on rails 如何在Rails中从一个模型更新和保存另一个模型?
在我的程序中,我有一个模型,卡路里,它计算一个人吃的东西,并给他们一个总分。在为每天的营养信息计算该分值之后,我想更新用户模型中的“points”变量 我在卡路里模型中的代码是Ruby on rails 如何在Rails中从一个模型更新和保存另一个模型?,ruby-on-rails,Ruby On Rails,在我的程序中,我有一个模型,卡路里,它计算一个人吃的东西,并给他们一个总分。在为每天的营养信息计算该分值之后,我想更新用户模型中的“points”变量 我在卡路里模型中的代码是 before_save :calculate_points def calculate_points # snipped calculations User.where(user_id).first.point_calculation end 在用户模型中,我有 def point_calculati
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
我通过在保存前创建回调来测试point_计算模型,它在那里运行良好。但是,在每次输入新的卡路里后进行更新比用户更新他们的设置更有意义。有什么建议吗?我错过了什么
谢谢您的帮助。我假设您的卡路里模型与用户有一种关系,并且用户有很多卡路里 在卡路里模型中:
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