假设我有一个Rails应用程序处理Posts和Comment对象。 A Post has_many
评论和每条评论belongs_to
a Post。使用rails辅助方法和控制器方法
每个评论有一个word_count
财产。帖子对象有一个average_comment_word_count
属性,它是每条评论的word_count
的平均值。
第一个问题是如果Post对象异步修改(添加的注释会影响平均字数),我应该在什么时候重新计算属性?当对象返回时?或每次添加新评论?它是否进入评论或发布帮助器方法?哪个控制器函数应该调用这个方法?
此外,当我包含以下Post助手方法时,我得到一个返回为JSON的NULL值。
def average_word_count
@average_word_count = 0
# current_user returns the current user object
# user has_many posts and each post belongs_to a user
current_user.posts.find(params[:id]).comments.each do |comment|
@average_word_count += comment.word_count/current_user.posts.find(params[:id]).comments.count
end
@average_word_count
end
这做了很多额外的查询*和*它没有考虑异步查询。 – coreyward 2012-04-16 21:15:37
@coreyward,关于异步查询的好点,但我没有看到额外的查询。每个post.comments.average(:foo)都会创建一个单独的sql语句。 – Mori 2012-04-16 22:38:21
我发现这种方法比客户计数器缓存更容易实现(也更通用),所以这就是为什么我将其标记为已接受。 – 2012-04-16 22:39:29