Suppose I have a Rails app that deals with Posts and Comments. A Post has_many Comments and each Comment belongs_to a Post.
Each Comment has a word_count property. The Post object has an average_comment_word_count property which is an average of each of the Comment’s word_count.
When I send a DELETE request on a particular comment, the app should recalculate the average_comment_word_count parameter. The way I thought it would work is like this:
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :post
after_destroy :update_post_average_word_count
def update_post_average_word_count
post_average_word_count = 0
post.comments.each do |comment|
post_average_word_count = post_average_word_count + comment.word_count
end
post_average_word_count / post.comments.count
post.update_attributes average_word_count: post_average_word_count
end
However I get a database error because the app cannot find a reference to the post in question (because the comment is gone, cue Homer Simpson here)
Is there a different method for accomplishing this?
Use
before_destroyand take this into account when calculating the post_average_word_count:post.update_attributes average_word_count: (post_average_word_count - self.word_count)