2
Posts
및 Comments
을 다루는 레일즈 애플리케이션이 있다고 가정합니다. A 포스트 has_many
코멘트와 각 코멘트 belongs_to
포스트.활성 레코드 콜백을 사용하여 모델 속성 업데이트
각 댓글의 글자는 word_count property
입니다. Post 개체는 각 word_count
의 평균 인 average_comment_word_count
속성을가집니다.
특정 의견에 대해 DELETE
요청을 보내면 앱에서 average_comment_word_count
매개 변수를 다시 계산해야합니다.
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
(주석이 사라지고 있기 때문에, 여기 호머 심슨 큐) : 나는 일 것이라고 생각하는 방법은 다음과 같이이다
이 작업을 수행하는 다른 방법이 있습니까? post_average_word_count을 계산할 때
을 나는 before_destroy' 내가 평균을 계산할 때 파괴되는 코멘트를 제외 할 필요가 없습니다 것'사용하는 경우? –
예, 그렇습니다. 'post.update_attributes average_word_count : (post_average_word_count - self.word_count)' – DanS
그리고 파괴 된 객체의 "소유자"를 보존 할 방법이 없습니까? 나는 이미'Comment'에 기록 된 메소드를 가지고 있으며, 메소드 중복을 피하려고합니다. (또는 모든 코드를'Post'로 옮깁니다.) –