我的Node
对象名为cached_comment_count
,我需要在创建新评论时对其进行更新。
这是我create
中的CommentsController
操作的一部分:
@node = Node.find(params[:node_id])
@comment = current_user.comments.new(comment_params)
@comment.node = @node
@node.cached_comment_count = @node.comments.count
但是,这不起作用,因为当我@node.comments.count
时,只会在保存新@node
之前返回@comment
对象上的当前评论。
如果我这样做会有什么作用:
@node.cached_comment_count += 1
这个问题的一个明显问题是,它只是一个增量1 - 并且感觉不完整。最好,最完整的方法是在保存完成后获取comments.count
。
但我不想最终陷入无限循环。
最好的方法是什么?
答案 0 :(得分:2)
只考虑counter_cache
rails功能。您可以查看旧版本的内容,但仍然很好Ryan Bates railscast
答案 1 :(得分:1)
您可以使用counter_cache
使用此声明,Rails将使缓存值保持最新,然后返回该值以响应size方法
in comment.rb
##should look something like this
##add this column in node table....comments_count
belongs_to :node, counter_cache: true
使用@ node.comments.size
答案 2 :(得分:0)
为什么不在Comment
模型中创建钩子后添加。
class Comment < ActiveRecord::Base
after_create :increment_comment_cache
private
def increment_comment_cache
self.node.update cached_comment_count: self.node.comments.count
end
end
然后从控制器中删除逻辑,删除行
@comment.node = @node
@node.cached_comment_count = @node.comments.count
这样,您可以通过非常干的方式更新缓存计数,从您创建评论的任何地方,它将自动为您更新计数