Ruby/Rails - Performing automatic calculations for a models attributes

前提是你 提交于 2019-12-13 03:45:10

问题


Im working on creating a game in rails and I ran into a problem for creating the scoring logic.

I have a model called Score which belongs to a user and has total_points as an attribute.

So every time a user creates a post(or whatever) I would like to automatically adjust the users total_score attribute.

I have a feeling that I could create a method somewhere in the score model but haven't done this before so I'm a bit confused.


回答1:


This is good use case for a ActiveRecord callback.

#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

Note: if the post is updatable, then you would want to use after_save, but my guess is after_create is what you are looking for

Good luck!



来源:https://stackoverflow.com/questions/6257431/ruby-rails-performing-automatic-calculations-for-a-models-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!