I have a Link that is an ActiveRecord object in Rails that has many Comments. Each comment has a score. I'm defining an instance variable @cumulative_score that keeps track of the sum of the score of all of the link's comments. Here is the link definition:
class Link < ActiveRecord::Base
has_many :comments
after_initialize :update_cumulative_score
def cumulative_score
@cumulative_score
end
def update_cumulative_score
total = 0
self.comments.each do |comment|
total = total + comment.score
puts "comment.score = #{comment.score}" # for debugging
end
@cumulative_score = total
puts "@cumulative_score = #{@cumulative_score}" # for debugging
end
end
I'm getting some strange results when I input the following into the rails console:
> link = Link.create
> link.cumulative_score
# returns 0
> comment = Comment.create(score: 20, link:link)
> link.reload
# puts debugging
comment.score = 20
total = 20
@cumulative_score = 20
> link.cumulative_score
# returns 0, NOT 20!
Why is the cumulative_score not changing itself to 20, when the puts statement is showing it is 20?
Thanks in advance!