ChrisWesAllen
ChrisWesAllen

Reputation: 4975

Ruby/Rails - Performing automatic calculations for a models attributes

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.

Upvotes: 0

Views: 575

Answers (1)

Jonathan
Jonathan

Reputation: 16349

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!

Upvotes: 5

Related Questions