假設我有一個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