[英]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.