2013-10-03 43 views
3

在我的程序中,我有一个模型卡路里,它需要一个人吃了什么,并给他们一个总分。在计算每天营养信息的点数值后,我想更新用户模型中的“点数”变量。如何在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模型,它的工作原理那里很好。但是在每次新卡路里输入之后进行更新会更有意义,而不是用户更新其设置。有什么建议?我错过了什么?

感谢您的帮助。

回答

2

我假设你的卡路里模型与用户和用户has_many卡路里has_one关系。

在卡路里模型:

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 
相关问题