[英]How do I update a counter of an associated object before it is saved?
我的Node
对象上有一个名为cached_comment_count
的属性,我需要在创建新注释时更新它。
这是我在CommentsController
create
动作的一部分:
@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
,只会在保存新的@comment
之前返回@node
对象上的当前注释。
如果我这样做,工作是什么:
@node.cached_comment_count += 1
这个问题的一个明显问题是,它只是一个增量1 - 并且感觉不完整。 最好,最完整的方法是在保存发生后获取comments.count
。
但我不想最终陷入无限循环。
什么是最好的方法来解决这个问题?
只需考虑counter_cache
rails功能。 您可以查看旧的,但仍然很好的Ryan Bates railscast
你可以使用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
为什么不在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
通过这种方式,您可以非常干燥地更新缓存计数,从您创建注释的任何位置,它将自动为您更新计数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.