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 don开发者_Go百科e this before so I'm a bit confused.
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!
精彩评论