ruby on rails - How do I update a counter of an associated object before it is saved? -


i have attribute on node object called cached_comment_count need updated whenever new comment created.

this part of create action in commentscontroller:

@node = node.find(params[:node_id]) @comment = current_user.comments.new(comment_params) @comment.node = @node @node.cached_comment_count = @node.comments.count 

however, doesn't work because when @node.comments.count returns current comments on @node object before new @comment saved.

what work if do:

@node.cached_comment_count += 1 

the obvious issue is increment of 1 - , doesn't feel complete. best, complete, way comments.count after save has taken place.

but don't want end in infinite loop.

what's best way approach this?

just consider counter_cache rails functionality. can check old, still ryan bates railscast


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -