[英]Ruby/Rails - Performing automatic calculations for a models attributes
我致力於在 Rails 中創建游戲,但在創建評分邏輯時遇到了問題。
我有一個名為 Score 的 model ,它屬於用戶,並且具有 total_points 作為屬性。
因此,每次用戶創建帖子(或其他任何內容)時,我都想自動調整用戶的 total_score 屬性。
我有一種感覺,我可以在 model 的某處創建一個方法,但之前沒有這樣做,所以我有點困惑。
這是 ActiveRecord 回調的好用例。
#post.rb
belongs_to :score
after_create :update_total_score
protected
def update_total_score
score.update_attribute :total_score, score.total_score + new_score_value
end
注意:如果帖子是可更新的,那么你會想使用 after_save,但我猜 after_create 是你要找的
祝你好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.