2013-10-03 38 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 
相關問題