多くのコメントを持つRailsのActiveRecordオブジェクトであるリンクがあります。各コメントにはスコアがあります。@cumulative_score
リンクのすべてのコメントのスコアの合計を追跡するインスタンス変数を定義しています。リンクの定義は次のとおりです。
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
Rails コンソールに次のように入力すると、奇妙な結果が得られます。
> 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!
putsステートメントが20であることを示しているのに、なぜcumulative_score
それ自体が20に変化しないのですか?
前もって感謝します!